const requesturl="https://wxserver.cards120.com"
Vue.use(vuePhotoPreview)
Vue.use(Quasar);
Vue.component('menu-item', {
    props: ['topic'],
    template: `
           <div>
            <q-item class="menu-item q-py-xs items-center" clickable v-if="topic.children.length">
              <img src="https://uploads-ssl.webflow.com/657c661418a503e0b43c9905/6582ea532471af5d4bcf5575_wenjianjia.svg" class="icon">
              <div class="texttopic" @click="showAlert(topic.topictitle)">{{ topic.topictitle }}</div>
              <q-icon name="chevron_right" class="toggle-icon" @click="toggle" right />
              <q-menu v-show="showSubmenu" anchor="top right" self="top left">
                <q-list>
                  <menu-item @topic-change="showAlert" v-for="child in topic.children" :key="child.topicid" :topic="child"></menu-item>
                </q-list>
              </q-menu>
            </q-item>
            <q-item class="menu-item q-py-xs items-center" clickable v-else @click="showAlert(topic.topictitle)">
              <img src="https://uploads-ssl.webflow.com/657c661418a503e0b43c9905/6582ea532471af5d4bcf5575_wenjianjia.svg" class="icon">
              <div class="texttopic" >{{ topic.topictitle }}</div>
            </q-item>
          </div>
        `,
    data() {
        return {
            showSubmenu: false
        };
    },
    methods: {
        toggle() {
            this.showSubmenu = !this.showSubmenu;
        },
         showAlert(title) {
             //迭代的组件不能这么进行监听，最上层监听不到。
             this.$emit('topic-change', title);

           }
    }
});
new Vue({
    el: '#xiangqingye', components: {draggable: window.vuedraggable},
    data: {
        allCards:[],
        draggedCard:{},
        dragOptions:{},
        //思维导图相关属性
        menuOpen:false,
        dialogOpen: false,
        lockStatus: false,
        theme: "",
        root: {},
        showMenuT: false,  // 初始状态设置为false，菜单不展开
        showMenu: false,
        topics: [],
        pdfHtmlString:"",
    	  showCheckboxes: false, // 控制多选框显示隐藏
      selectedCards: [], // 存储选中的卡片的 ID
        zhengmianbeimianshow:false,
        globalOrder:0,
        checkjihuo:false,
        pdfUrl: null, // 用于存储生成的PDF URL
        showModal: false, // 控制模态框是否显示
        ifbianjidonghua:true,
        ifbianji:false,
        ifpiliangdianjiShanChu:false,
        editTitleChange:false,
        currentCardIndex: -1, // 默认值为-1，表示没有卡片被选中
        showModal: false,
        EditOrAdd:0, // 0是编辑 1是新增
        searchQuery: '',
        onlyStarred: false,
        isRandomMode: false,
        autoPlayTimer: null,
        activeIndex: null,
        zhongjianka: null,
        uid: "",
        currentIndex: 0,
        dangqianzhuti: "",
        dangqianzhutititle: "",
        orderFromStorage: "",
        previewCards: [],
        piliangdianjiCard:null,
        ifpiliangdianjiCard:false,
    },
    created() {

    },
    computed: {

        currentCard() {
            if (this.previewCards && this.previewCards.length > 0) {

                return this.previewCards[this.currentIndex];
            }
            return {back: '', front: '', id: null, mark: 0};
        },
        currentCardWithTheme() {
            // 检查 currentCard 是否有效
            if (!this.currentCard || !this.currentCard.id) return null;

            // 从 localStorage 中获取 cards
            const cards = JSON.parse(localStorage.getItem('cards'));
            if (!cards) return this.currentCard; // 如果没有 cards，返回原始的 currentCard

            // 查找包含 currentCard 的主题名称
            let themeName = null;
            for (const theme in cards) {
                if (!cards.hasOwnProperty(theme)) continue;
                if (theme === "所有卡片") continue;
                if (cards.hasOwnProperty(theme)) {
                    const themeCards = cards[theme].previewCards || [];
                    const found = themeCards.some(card => card.id === this.currentCard.id);
                    if (found) {
                        themeName = theme;
                        break; // 找到后退出循环
                    }
                }
            }

            // 返回一个新对象，是 currentCard 的拷贝，并附加 theme 属性
            return { ...this.currentCard, cardTheme: themeName };
        },
        filteredCards() {
            // 首先为每张卡片添加额外的 frontTopic 属性
            var cardsWithFrontTopic = ""
            if(localStorage.getItem("dangqianzhuti")==="所有卡片"){
                cardsWithFrontTopic = this.previewCards.map(card => ({
                    ...card,
                    frontTopic: `${card.topicname}：${card.front}`, // 假设这是合并的格式

                }));
            }else {
                cardsWithFrontTopic = this.previewCards.map(card => ({
                    ...card,
                    frontTopic: `${card.front}`, // 假设这是合并的格式

                }));
            }


            // 基于新的 frontTopic 字段进行过滤
            if (this.searchQuery.trim() === '') {
                return cardsWithFrontTopic;
            } else {
                return cardsWithFrontTopic.filter(card =>
                    card.frontTopic.toLowerCase().includes(this.searchQuery.toLowerCase())
                );
            }
        }
    },
    methods: {
        getAllTopicNamesFromZhuti() {
            // 从 localStorage 获取 zhuti 数据
            const zhutiStr = localStorage.getItem('zhuti');
            if (!zhutiStr) {
                console.error('No zhuti data available in localStorage');
                return [];
            }

            // 解析 zhuti 数据为 JSON 对象
            const zhuti = JSON.parse(zhutiStr);
            const topics = zhuti.topics; // 假设 topics 是一个数组

            // 递归函数，用于收集所有主题名称
            const topicNames = [];
            function collectTopicNames(topicsArray) {
                for (const topic of topicsArray) {
                    topicNames.push(topic.topicname); // 收集当前主题名称
                    // 如果当前主题有子主题，则递归处理子主题
                    if (topic.children && topic.children.length > 0) {
                        collectTopicNames(topic.children);
                    }
                }
            }

            // 开始从顶级主题收集名称
            collectTopicNames(topics);

            return topicNames;
        },


        initSimMind(){

            return new Promise((resolve, reject) => {
            let jsonStr = ""
            const rootMind = localStorage.getItem("rootMind")

            function parseTopic(topic) {
                const node = {
                    data: {
                        text: topic.topicname,
                        fold: 1,
                        id: topic.topicid,
                        topicid:topic.topicid
                    },
                    children: []
                };

                // 处理子主题
                topic.children.forEach(child => {
                    node.children.push(parseTopic(child));
                });

                // 处理 newOrderName 和 order，将其分割后作为独立的子节点
                console.log(topic);
//topic.topicname todo
                let topicname = topic.topicname
                const cardsData = localStorage.getItem('cards');
                if (!cardsData) {
                    return 'No data available';  // 如果没有数据则返回提示
                }

                // 解析存储的字符串为对象
                const cardsObj = JSON.parse(cardsData);
                if (!cardsObj[topicname] || !cardsObj[topicname].previewCards) {
                    return 'Topic not found or no cards available';  // 如果找不到topic或者下面没有卡片则返回提示
                }
                topic.newOrderName = cardsObj[topicname].previewCards.map(card => card.front.replace(/<\/?p>/g, "")).join('__SEP__');
                topic.order = cardsObj[topicname].previewCards.map(card => card.id).join(',');


                if (topic.newOrderName) {
                    const orderNames = topic.newOrderName.split('__SEP__');
                    const topicid = topic.topicid;
                    const orders = topic.order.split(',');
                    orderNames.forEach((name, index) => {
                        node.children.push({
                            data: {
                                text: name,
                                id: orders[index],  // 确保数组索引不会越界
                                fold:0,
                                topicid:topicid


                            }
                        });
                    });
                }

                return node;
            }
            if(rootMind===null){
                jsonStr = localStorage.getItem('zhuti')





                // 加载原始 JSON 数据
                const data = JSON.parse(jsonStr);

                // 构建新的 JSON 结构
                const newJsonStructure = {
                    data: {
                        text: "所有主题",
                        id:'11111',
                        fold:0,
                        topicid:'11111'

                    },
                    children: []
                };

                // 解析所有主题
                data.topics.forEach(topic => {
                    newJsonStructure.children.push(parseTopic(topic));
                });

                // 输出结果
                console.log(JSON.stringify(newJsonStructure, null, 4));

                this.root = newJsonStructure;
            }else{

                this.root = JSON.parse(rootMind)
                //   同步流程，更新信息
                
                console.log("======================================================")
                function collectFoldZeroNodes(node) {
                    // 初始化结果数组
                    let results = [];

                    // 递归函数，用于深度遍历节点树
                    function traverse(node, collected) {
                        if (node.data.fold === 1) {
                            // 当前节点是 fold=1 的节点，重置收集数组
                            collected = {
                                parentNode: node.data, // 存储当前 fold=1 的节点
                                childNodes: []         // 用于存储所有直接的 fold=0 子节点
                            };
                            results.push(collected); // 将此对象加入结果列表
                        } else if (node.data.fold === 0 && collected) {
                            // 当前节点是 fold=0 的节点，并且有一个有效的收集器
                            collected.childNodes.push(node.data); // 将此节点加入当前收集器的子节点列表
                        }

                        // 遍历子节点
                        if (node.children) {
                            for (let child of node.children) {
                                traverse(child, collected);
                            }
                        }

                        // 当遍历到 fold=1 的节点或者没有子节点时，终止当前分支的进一步收集
                        if (node.data.fold === 1 || !node.children || node.children.length === 0) {
                            return;
                        }
                    }

                    // 从根节点开始遍历
                    traverse(node, null);

                    return results;
                }

                let results = collectFoldZeroNodes(this.root);
                console.log(JSON.stringify(results, null, 2));




                function compareAndCollectMissingCards(results, cardsFromStorage) {
                    let missingCards = [];

                    // 遍历所有 fold=1 的节点及其子节点信息
                    results.forEach(result => {
                        let parentNode = result.parentNode;
                        let existingChildIds = result.childNodes.map(child => child.id);

                        // 获取相应主题下的所有卡片
                        let topicCards = cardsFromStorage[parentNode.text] ? cardsFromStorage[parentNode.text].previewCards : [];

                        // 查找和添加缺失的卡片
                        topicCards.forEach(card => {
                            // 如果 result 中的子节点不包括此卡片的id，则认为是缺失的
                            if (!existingChildIds.includes(card.id)) {
                                missingCards.push({
                                    text: card.front, //
                                    id: card.id,       // 使用卡片的 id
                                    fold: 0,           // 设置 fold 为 0
                                    topicid: parentNode.id // 父节点的 id 作为 topicid
                                });
                            }
                        });
                    });

                    return missingCards;
                }

// 示例：获取 localStorage 中存储的 cards 数据
                let cardsFromStorage = JSON.parse(localStorage.getItem('cards') || '{}');

// 假设 rootNode 是之前定义的根节点


// 比较并获取缺失的卡片
                let missingCards = compareAndCollectMissingCards(results, cardsFromStorage);

                console.log("Missing Cards:", JSON.stringify(missingCards, null, 2));

                //找到了，找到之后更新树

                function addMissingCardsToTree(root, missingCards) {
                    function traverseAndUpdate(node) {
                        if (node.data && missingCards.some(card => card.topicid === node.data.id)) {
                            // 找到与当前节点匹配的所有缺失卡片
                            let matchedCards = missingCards.filter(card => card.topicid === node.data.id);
                            if (!node.children) {
                                node.children = [];  // 如果当前没有children数组，初始化一个空数组
                            }
                            // 将匹配的卡片转换为节点并添加到children数组中
                            matchedCards.forEach(card => {
                                node.children.push({
                                    data: {
                                        text: card.text,
                                        id: card.id,
                                        fold: card.fold,
                                        topicid:card.topicid
                                    },
                                    children: []  // 新添加的节点暂时没有子节点
                                });
                            });
                        }

                        // 递归遍历子节点
                        if (node.children) {
                            node.children.forEach(child => traverseAndUpdate(child));
                        }
                    }

                    // 从根节点开始遍历和更新
                    traverseAndUpdate(root);
                }


                
                //==========================反过来找缺失关系，找到缺失的之后删除思维导图

                function compareAndCollectTrueReverseMissingCards(results, cardsFromStorage) {
                    let trulyReverseMissingCards = [];

                    // 遍历结果集中的每一个主题及其卡片
                    results.forEach(result => {
                        let parentNode = result.parentNode;

                        // 从存储中获取与当前结果节点对应的主题的卡片数组
                        let topicCards = cardsFromStorage[parentNode.text] ? cardsFromStorage[parentNode.text].previewCards : [];

                        result.childNodes.forEach(childNode => {
                            // 检查结果集中的每个子节点（卡片）是否在主题卡片数组中
                            let isPresentInStorage = topicCards.some(card => card.id === childNode.id);

                            // 如果在结果集中的卡片没有在主题卡片数组中找到，则认为是缺失的
                            if (!isPresentInStorage) {
                                trulyReverseMissingCards.push({
                                    text: childNode.text,  // 使用卡片的 text 属性
                                    id: childNode.id,     // 卡片的 id
                                    fold: 0,              // 设置 fold 为 0
                                    topicid: parentNode.id  // 使用父节点的 id 作为 topicid
                                });
                            }
                        });
                    });

                    return trulyReverseMissingCards;
                }

// 调用函数并打印结果
                let trulyReverseMissingCards = compareAndCollectTrueReverseMissingCards(results, cardsFromStorage);
                console.log("Truly Reverse Missing Cards:", JSON.stringify(trulyReverseMissingCards, null, 2));


                function removeMissingNodesFromTree(tree, missingCards) {
                    // 递归函数用于遍历和可能删除节点
                    function traverseAndRemove(node, parentId) {
                        if (!node.children) return;  // 如果没有子节点，直接返回

                        // 过滤子节点列表，排除那些在missingCards中的节点
                        node.children = node.children.filter(child => {
                            // 检查此节点是否应该被删除
                            let shouldRemove = missingCards.some(missingCard => missingCard.id === child.data.id);
                            return !shouldRemove;
                        });

                        // 递归遍历更新后的子节点列表
                        node.children.forEach(child => {
                            traverseAndRemove(child, node.data.id);  // 传递当前节点ID作为父ID
                        });
                    }

                    // 从根节点开始遍历
                    traverseAndRemove(tree);
                }

// 示例：假设你已经有了trulyReverseMissingCards和rootNode（tree结构）




                const zhuti = JSON.parse(localStorage.getItem('zhuti'));
                const topicsTree = zhuti.topics;  // 从zhuti中获取topics属性
                //   更新流程 todo




                // 步骤 1: 解析 JSON 树结构
                // const rootMind = localStorage.getItem('rootMind');  // 假设rootMind是一个存储在localStorage的JSON字符串
                const tree = JSON.parse(rootMind);


                // =================================增删

                addMissingCardsToTree(tree, missingCards);
                removeMissingNodesFromTree(tree, trulyReverseMissingCards);

                console.log("Updated simmind tree:", JSON.stringify(this.root, null, 2));

                //============


                const targetIdsFold = [];
                const findNodesFoldAndCollectTopics = (node, topics) => {
                    if (node.data && node.data.fold === 1) {
                        // 查找匹配的topic
                        const matchedTopic = findTopicById(topics, node.data.id);
                        if (matchedTopic) {
                            targetIdsFold.push({ topicid: matchedTopic.topicid, topicname: matchedTopic.topicname });
                        }
                    }
                    if (node.children) {
                        node.children.forEach(child => findNodesFoldAndCollectTopics(child, topics));
                    }
                };

                const findTopicById = (topics, id) => {
                    for (const topic of topics) {
                        if (topic.topicid === id) {
                            return topic;
                        }
                        if (topic.children) {
                            const found = findTopicById(topic.children, id);
                            if (found) {
                                return found;
                            }
                        }
                    }
                    return null;
                };
                findNodesFoldAndCollectTopics(tree, topicsTree);


                // 步骤 3: 更新tree中对应节点的data.text
                const updateNodeText = (node, targetIdsFold) => {
                    if (node.data) {
                        const matchedTopic = targetIdsFold.find(topic => topic.topicid === node.data.id);
                        if (matchedTopic) {
                            node.data.text = matchedTopic.topicname;
                        }
                    }
                    if (node.children) {
                        node.children.forEach(child => updateNodeText(child, targetIdsFold));
                    }
                };
                updateNodeText(tree, targetIdsFold);



// 步骤 2: 查找所有fold为0的节点
                const targetIds = [];
                const findNodes = (node) => {
                    if (node.data.fold === 0) {
                        targetIds.push(node.data.id);
                    }
                    if (node.children) {
                        node.children.forEach(child => findNodes(child));
                    }
                };
                findNodes(tree);




// 步骤 3: 匹配和更新数据
                const cards = JSON.parse(localStorage.getItem('cards'));
                targetIds.forEach(id => {

                    Object.keys(cards).filter(key => key !== "所有卡片").forEach(key => {
                        const value = cards[key];
                        // Object.values(cards).forEach(value => {  // 遍历cards中的每一个value


                        const card = value.previewCards.find(card => card.id === id);  // 从preview属性中查找卡片
                        if (card) {
                            // 更新树结构中对应节点的text属性
                            const updateText = (node) => {
                                if (node.data.id === id) {
                                    node.data.text = card.front.replace(/<\/?p>/g, "");
                                }
                                if (node.children) {
                                    node.children.forEach(child => updateText(child));
                                }
                            };
                            updateText(tree);
                        }



                    });



                });

                // ================================================== 主题同步上
                // Step 1: 查找所有 fold 为 1 的节点 ID
                const foldIds = [];
                const collectFoldIds = (node) => {
                    if (node.data && node.data.fold === 1) {
                        foldIds.push(node.data.id);
                    }
                    if (node.children) {
                        node.children.forEach(child => collectFoldIds(child));
                    }
                };
                collectFoldIds(tree);

                // Step 2: 获取 zhuti 中的所有主题 ID
                const allTopicIds = [];
                const collectAllTopicIds = (topic) => {
                    allTopicIds.push(topic.topicid);
                    if (topic.children) {
                        topic.children.forEach(child => collectAllTopicIds(child));
                    }
                };
                topicsTree.forEach(topic => collectAllTopicIds(topic));

                // Step 3: 查找 zhuti 中不在 foldIds 中的主题
                const missingTopics = topicsTree.filter(topic => !foldIds.includes(topic.topicid));

                // Step 4: 将 missingTopics 添加到树结构中
                missingTopics.forEach(missingTopic => {
                    tree.children.push(parseTopic(missingTopic));
                });







// 步骤 4: 更新localStorage中的rootMind
                localStorage.setItem('rootMind', JSON.stringify(tree));

                this.root = JSON.parse(localStorage.getItem('rootMind'));
                this.root._updata=true;


                this.theme = "fresh-green-compat";

            }

                setTimeout(()=>{

                    // 获取具有特定类名的元素
                    const divButton = document.querySelector('.icon-ungroup');

// 定义一个函数来模拟几乎同时的点击
                    function simulateSimultaneousClicks(clicksCount) {
                        for (let i = 0; i < clicksCount; i++) {
                            setTimeout(() => {
                                divButton.click();  // 模拟点击
                                console.log(`第 ${i + 1} 次点击`);
                            }, 1 * i); // 微小的延迟增量确保它们不是完全同时，但非常接近
                        }
                    }

// 模拟几乎同时点击4次
                    simulateSimultaneousClicks(4);


                },1000)

                resolve(); // 完成更新，返回 resolve


            });









        },
        initSimMindOld(){
            const jsonStr = localStorage.getItem('zhuti')


            function parseTopic(topic) {
                const node = {
                    data: {
                        text: topic.topicname,
                        fold: 1,
                        id: topic.topicid
                    },
                    children: []
                };

                // 处理子主题
                topic.children.forEach(child => {
                    node.children.push(parseTopic(child));
                });

                // 处理 newOrderName 和 order，将其分割后作为独立的子节点
                console.log(topic);

                if (topic.newOrderName) {
                    const orderNames = topic.newOrderName.split(',');
                    const orders = topic.order.split(',');
                    orderNames.forEach((name, index) => {
                        node.children.push({
                            data: {
                                text: name,
                                id: orders[index]  // 确保数组索引不会越界
                            }
                        });
                    });
                }

                return node;
            }

// 加载原始 JSON 数据
            const data = JSON.parse(jsonStr);

// 构建新的 JSON 结构
            const newJsonStructure = {
                data: {
                    text: "所有主题"
                },
                children: []
            };

// 解析所有主题
            data.topics.forEach(topic => {
                newJsonStructure.children.push(parseTopic(topic));
            });

// 输出结果
            console.log(JSON.stringify(newJsonStructure, null, 4));

            this.root = newJsonStructure;
            this.root._updata=true;


            this.theme = "fresh-green-compat";

        },
        bigModelShow(event){
            this.menuOpen = false
            this.showMenu = false
            // 阻止默认行为和事件传播
            event.preventDefault();
            event.stopPropagation();
        },
        topicShow(event){
            this.menuOpen = false
            this.showMenu =! this.showMenu
            // 阻止默认行为和事件传播
            event.preventDefault();
            event.stopPropagation();
        },

        toggleStyleForMind(){
            var styleElement = document.getElementById('dynamicStyles');

            // 检查是否已经存在style元素 if(this.menuOpen){}
            if (!this.menuOpen && styleElement) {
                styleElement.remove(); // 如果存在，移除该style元素
            } else if(this.menuOpen && !styleElement) {
                // 如果不存在，创建并添加style元素
                var style = document.createElement('style');
                style.id = 'dynamicStyles';
                style.type = 'text/css';


                style.innerHTML = `
            
            .sidebarright {
                width: 55%!important;
            }
            .maincontent {
                width: 50%!important;
            }
            .contextmenu {
                z-index: 100000!important;
            }
            .contextmenu .menu {
                width: 1000px!important;
                max-width: 150px!important;
            }
            .edtior {
                position: fixed; 
                left: 57px!important;
                top: 16px!important;
                height: 0;
                overflow: visible;
                z-index: 1000;
            }
            .btn-warper, .title, .editor-text1, .imagelist, .urllist, .editor-input {
                position: absolute;
                top: 50px;
                right: 10px;
                width: auto;
                z-index: 1000;
            }
            .editor-text1 {
                z-index: 1000;
            }
            .image-upload, .editor-input {
                width: 200px;
                height: auto;
                z-index: 1000;
            }
            .image-cover, .btn-cancel, .btn-sure {
                width: 100%;
                z-index: 1000;
            }
            @keyframes enter {
                from {
                    transform: translateY(-300px);
                }
                to {
                    transform: translateY(0);
                }
            }
            
        `;
                document.head.appendChild(style);
            }
        },
        simMindMenu(event){

            // 阻止默认行为和事件传播
            event.preventDefault();
            event.stopPropagation();



            this.showMenu = false
            this.menuOpen = !this.menuOpen;

            // this.initSimMind()
            this.initSimMind()
                .then(() => {

                    // 切换思维导图样式
                    this.toggleStyleForMind();
                })
            this.toggleStyleForMind();
            // this.toggleStyleForMind()

            //数据重新渲染


            // 阻止默认行为和事件传播
            event.preventDefault();
            event.stopPropagation();
        },

        mindCardEdit(e){
            // 找到原始内容 e.node
            console.log("mindCardEdit")
            document.getElementById('bianjianniu').click()
            return;
            var index = this.orderActivities.findIndex(a => {
                let texttemp =  a.front.split("：").length > 1?a.front.split("：")[1]:a.front.split(":")[1]
                return texttemp == e.card.node
            })

            this.card = this.orderActivities[index]
            this.editCard()
            this.mindMapUpdateNode = {node:e.node,data:e.card.node,id:e.card.id}

        },
        // 卡片移动到新目录中
        FromCardToFold: function (topicId,parenttopicid,cardid,e) {


            let topicname = this.getTopicNameById(topicId)
            let parenttopicname = this.getTopicNameById(parenttopicid)
            // Retrieve the current theme from localStorage
            const currentThemeId = topicname;
            // Assuming cards are stored in an array under each theme's 'previewCards' key in localStorage
            const themes = JSON.parse(localStorage.getItem('cards')) || {};
            const currentTheme = themes[currentThemeId];


            // const targetTopicIndex = this.topiczu.findIndex(topic => topic.topicid === topicId);
            var targetTopicTitle = ""
            // if(targetTopicIndex===-1){
            //     //没有拖放到正确位置
            //     if(breadTitle===''){
            //         return ;
            //     }
            //     targetTopicTitle = breadTitle
            // }else{
            //     targetTopicTitle = this.topiczu[targetTopicIndex].topictitle
            // }
            targetTopicTitle= parenttopicname
            //拽到面包屑导航的当前文件夹，则内容不变,将位置提前
            // 拽到面包屑导航的当前文件夹，则内容不变,位置提前
            if (targetTopicTitle === currentThemeId) {
                // // 找到拖拽的卡片在当前主题previewCards数组中的位置
                // const cardIndex = currentTheme.previewCards.findIndex(card => card.id === this.draggedCard.id);
                // if (cardIndex > -1) {
                //     // 从数组中移除该卡片
                //     currentTheme.previewCards.splice(cardIndex, 1);
                //     // 将卡片重新插入到数组的开头
                //     currentTheme.previewCards.unshift(this.draggedCard);
                // }
                // this.draggedCard.lastmodifieddate = new Date().toISOString().slice(0, 19).replace('T', ' ');
                // // 不需要进一步处理，直接更新localStorage并返回
                // localStorage.setItem('cards', JSON.stringify(themes));
                // return;
                return;
            }

            //从 id 找到在cards中找到这个卡片

            // 从 localStorage 读取 cards 数据
            const cardsJson = localStorage.getItem('cards');
            if (cardsJson) {
                // 解析 JSON 数据
                const cardsObj = JSON.parse(cardsJson);

                // 遍历对象中的键值对
                for (let key in cardsObj) {
                    // 跳过 '所有卡片' 键
                    if (key !== '所有卡片') {
                        const previewCards = cardsObj[key].previewCards;

                        // 在 previewCards 数组中查找指定的 cardid
                        const foundCard = previewCards.find(card => card.id === cardid);



                        // 如果找到了卡片，执行需要的操作
                        if (foundCard) {
                            console.log('找到的卡片:', foundCard);
                            this.draggedCard = foundCard
                            // 在这里可以根据需要对 foundCard 进行操作
                            break;
                        }
                    }
                }
            } else {
                console.log('在 localStorage 中没有找到 cards 数据');
            }
            

            const currentThemeDragTo = themes[targetTopicTitle];
            if (!currentThemeDragTo) {
                themes[targetTopicTitle] = {'order': '', 'previewCards': []}
            }
            this.draggedCard.lastmodifieddate = new Date().toISOString().slice(0, 19).replace('T', ' ')
            this.draggedCard.topicname = targetTopicTitle

            // 假设 themes 是你的对象，targetTopicTitle 是你要操作的目标主题
            if (!themes[targetTopicTitle]) {
                // 如果 themes 对象中不存在 targetTopicTitle，先初始化这个键值对
                Vue.set(themes, targetTopicTitle, { previewCards: [] });
            } else if (!themes[targetTopicTitle].previewCards) {
                // 如果 themes[targetTopicTitle] 存在但没有 previewCards 属性，就初始化为数组
                Vue.set(themes[targetTopicTitle], 'previewCards', []);
            }
            themes[targetTopicTitle].previewCards.unshift(this.draggedCard)
            console.log("🚀 ~ file: cardzhuye-vue.js ~ line 222 ~ themes: ",themes);



            if (currentTheme && currentTheme.previewCards) {
                // Filter out the card that matches this.draggedCard's ID
                const updatedPreviewCards = currentTheme.previewCards.filter(card => card.id !== this.draggedCard.id);

                // Update the theme with the new list of previewCards
                currentTheme.previewCards = updatedPreviewCards;
                themes[currentThemeId] = currentTheme;
                // Update localStorage
            }


            localStorage.setItem('cards', JSON.stringify(themes));
            this.cardsTurnCards2ES()
            this.save_xinzengids(this.draggedCard.id)
            e.node.data.topicid = parenttopicid


        },
        cardsTurnCards2ES: function () {
            const cards1 = JSON.parse(localStorage.getItem('cards'));

            if (cards1 && typeof cards1 === 'object') {
                let latestUpdateTime = new Date(0); // 设置初始最早的时间
                let latestCardId = null;
                Object.keys(cards1).forEach(key => {
                    let card = cards1[key];
                    //如果card下的previewCards不存在
                    if (card.previewCards !== undefined) {
                        card.previewCards.forEach(previewCard => {
                            if ('front' in previewCard) previewCard.front = key + '：' + previewCard.front;
                            ;
                            if ('mark' in previewCard) {
                                previewCard.known = previewCard.mark;
                                delete previewCard.mark;
                            }
                            ;
                            if ('id' in previewCard) {
                                previewCard.sqlId = previewCard.id;
                                delete previewCard.id;
                            }
                            ;
                            if ('time' in previewCard) {
                                previewCard.createtime = previewCard.time;
                                delete previewCard.time;
                            }
                            ;
                            if ('lastmodifieddate' in previewCard) {
                                previewCard.lastmodifieddate = previewCard.lastmodifieddate;
                                delete previewCard.updatetime;
                                delete previewCard.icon;
                                delete previewCard.size;
                            }
                            ;previewCard.uid = this.uid;
                            previewCard.type = 1;


                            // 更新最近修改的卡片ID
                            const currentUpdateTime = new Date(previewCard.lastmodifieddate);
                            if (currentUpdateTime > latestUpdateTime) {
                                latestUpdateTime = currentUpdateTime;
                                latestCardId = previewCard.sqlId;
                            }

                        });
                    }
                });
                console.log("🚀 ~ file: cardperform.html ~ line 428 ~ latestCardId: ", latestCardId);
                // this.save_xinzengids(latestCardId) todo 有争议需要讨论
                localStorage.setItem('cards2es', JSON.stringify(cards1))
                this.loadAndSortCards()
            }
        },
        loadAndSortCards() {
            // 从localStorage读取cards2es数据
            const cards2es = JSON.parse(localStorage.getItem('cards2es')) || {};

            // 从cards2es中读取所有previewCards中的卡片
            let cards = [];
            Object.keys(cards2es).forEach(key => {
                if(key==="所有卡片") return;
                if (cards2es[key].previewCards) {
                    cards = cards.concat(cards2es[key].previewCards);
                }
            });

            // 按照修改时间排序卡片
            cards.sort((a, b) => {
                const aTime = new Date(a.modifiedTime).getTime();
                const bTime = new Date(b.modifiedTime).getTime();
                return bTime - aTime; // 降序排序
            });


            // Object.keys(cards).forEach(key => {
            //     let card = cards[key];
            //     //如果card下的previewCards不存在
            //     if (card.previewCards !== undefined) {
            //         card.previewCards.forEach(previewCard => {
            //             previewCard.id = previewCard.sqlId;
            //
            //
            //
            //
            //         });
            //     }
            // });



            // 更新allCards数据
            this.allCards = [...cards];
        },
        minddragend(e){
            let id = e.data.id
            let topicid = e.data.topicid
            let parenttopicid = e.node.parent.data.topicid
            this.FromCardToFold(topicid,parenttopicid,id,e)
            this.mindcommonSave()
            console.log("minddragend")
            return;
            console.log("minddragend事件传递")
            console.log(e)
            //获取需要修改的card
            /**todo 每个节点的数据都不能一样不然就会混乱逻辑,修改使用id匹配解决这个问题。
             * bug
             * node1 '1'
             * node3 '51'
             *
             * card变成node3了，后续操作就错了，换成 == 就ok了
             */
            var index = this.orderActivities.findIndex(a => a.id == e.data.id)
            var card = this.orderActivities[index]
            // 各种情况下不发送drag完成的请求，相对位置没改变，drag之后原来listsameLevelId=0和e.top为0表示首位，同层首位
            // 左边和上边一样的话，这个位置就不变，就不进行后续操作

            if(card.mindmapParentId == e.left &&card.mindmapSameLevelId == e.top){
                console.log("相对位置没变，所有drag不生效,首位问题除外")
                return
            }

            card.mindmapLayer = e.layer
            if(e.layer!=0){

                let leftIndex = this.orderActivities.findIndex(json => json.id==e.left)
                card.mindmapParentId=this.orderActivities[leftIndex].id
            }else{
                card.mindmapParentId = 0
            }

            if(e.top==""){
                // 表示是头节点，查询的时候刚开始就要插入，如果有两个头结点按照最新的插入
                card.listSameLevelId=-1
            }else{
                let topIndex = this.orderActivities.findIndex(json => json.id==e.top)
                card.mindmapSameLevelId=this.orderActivities[topIndex].id
                card.listSameLevelId=0
            }
            // 更新这个card
            this.editCard(card)
            this.edit_save_card_ES_Only()
            console.log(card)

        },
        mindeditShow:function(e){
            console.log("mindeditShow")
            return;
            console.log("mindeditShow")
            var self = this
            // self.card.back=""
            self.show=""


        },




        mindcommonSave(){

            document.querySelector('.icon-save').click();
            // 保存之后，需要同步，还是只在最后同步

            //更新主题
            // 从 localStorage 中获取 zhuti 并解析为 JSON 对象
            let zhuti = localStorage.getItem('zhuti');
            if (zhuti) {
                zhuti = JSON.parse(zhuti);
            } else {
                zhuti = {};
            }

// 从 localStorage 中获取 rootMind
            const rootMind = localStorage.getItem('rootMind');

// 将 rootMind 属性添加到 zhuti 对象中
            zhuti.rootMind = JSON.parse(rootMind);

// 将更新后的 zhuti 对象写回 localStorage
            localStorage.setItem('zhuti', JSON.stringify(zhuti));


        },
        mindrollback:function(){
            console.log("mindrollback")
            document.getElementById('simmindbtn').click()
            this.mindcommonSave()
            localStorage.setItem('maxEditTimeZhuti', '0');
            return;
            this.cancelMindShow=false
            // console.log("全屏思维导图")
            // this.fullScreen(document.getElementsByClassName('baidumind'))
        },
        //全屏
        fullScreen:function(el) {

            console.log("fullScreen")
            return;
            var rfs = el.requestFullScreen || el.webkitRequestFullScreen || el.mozRequestFullScreen || el.msRequestFullScreen,
                wscript;

            if(typeof rfs != "undefined" && rfs) {
                rfs.call(el);
                return;
            }

            if(typeof window.ActiveXObject != "undefined") {
                wscript = new ActiveXObject("WScript.Shell");
                if(wscript) {
                    wscript.SendKeys("{F11}");
                }
            }
        },

        //退出全屏
        exitFullScreen:function(el) {

            console.log("exitFullScreen")
            return;

            var el= document,
                cfs = el.cancelFullScreen || el.webkitCancelFullScreen || el.mozCancelFullScreen || el.exitFullScreen,
                wscript;

            if (typeof cfs != "undefined" && cfs) {
                cfs.call(el);
                return;
            }

            if (typeof window.ActiveXObject != "undefined") {
                wscript = new ActiveXObject("WScript.Shell");
                if (wscript != null) {
                    wscript.SendKeys("{F11}");
                }
            }
        },
        mindHeadleCancel:function(value){
            console.log("mindHeadleCancel")
            return;

            console.log("cancel的时候顺便去掉思维导图的显示框")
            this.cancelMindShow = false



        },
        // 更新事件监听mindEditNode mindRemoveNode 找到这个节点数据，然后再进行其他操作，去掉监控方式
        mindRemoveNode:function(value){
            console.log("mindRemoveNode")
            this.deleteCard(value.data)
            return;
            // this.cancelMindShow = true

            var self_ = this
            console.log("节点删除")
            console.log(value)
            // 节点内容text修改


            //



            var orderIndex = self_.orderActivities.findIndex(json => json.id==value.id)
            if(orderIndex!=-1){
                self_.quickDelete(orderIndex)
                self_.orderActivities.remove(orderIndex)
            }
            this.mindcommonSave()

        },

        getTopicNameById(topicId) {
            // 从localStorage获取zhuti数据
            const zhutiStr = localStorage.getItem('zhuti');
            if (!zhutiStr) {
                console.error('No zhuti data available in localStorage');
                return null;
            }

            const zhuti = JSON.parse(zhutiStr);
            const topics = zhuti.topics; // 假设顶级节点数组存储在zhuti.topics

            // 递归函数搜索特定topicid
            function searchTopic(topics, topicId) {
                for (const topic of topics) {
                    if (topic.topicid === topicId) {
                        return topic.topicname;  // 找到匹配的topicid, 返回topicname
                    }
                    // 如果当前节点有子节点, 继续递归搜索
                    if (topic.children) {
                        const found = searchTopic(topic.children, topicId);
                        if (found) return found; // 如果在子节点中找到匹配的topicid, 返回找到的topicname
                    }
                }
                return null;  // 如果没有找到匹配的topicid, 返回null
            }

            // 开始搜索所有主题
            return searchTopic(topics, topicId);
        },

        mindEditNode:function(value){

            let topicName =""
            if(value.dataPre===value.dataAfter) return;

            let nodeid = value.dataTotal.nodeData.id
            let topicid = value.dataTotal.nodeData.topicid
            let nodefront = value.dataAfter
            let nodefold = value.dataTotal.nodeData.fold
            //找到这个卡片，然后更新front值，就是将这个卡片信息带入到更新卡片中
            if(nodefold===0){

                topicName = this.getTopicNameById(topicid);
                console.log('Topic Name:', topicName);
                if(topicName===localStorage.getItem('dangqianzhuti')){

                }else{
                    //dangqianzhutititle
                    localStorage.setItem('dangqianzhuti',topicName)
                    localStorage.setItem('dangqianzhutititle',topicName)

                }
                // this.initmount(topicName)
                //切换主题
                this.initmount(topicName).then(() => {
                    const cardId = nodeid;

                    const previewCards = this.previewCards;
                    const cardIndex = previewCards.findIndex(card => card.id === cardId);
                    console.log('Card Index:', cardIndex);
                    if (cardIndex !== -1) {
                        // this.dianjishijianxian_kapian(cardIndex)
                        this.dianjishijianxian_kapian(cardIndex).then(result => {

                            //修改
                            this.EditOrAdd = 0
                            // var textarea = nodefront;
                            var fronttextarea = nodefront;
                            // var editor = tinymce.get('myTextarea');
                            var backtextarea = this.currentCard.back;
                            const cardIndex = this.previewCards.findIndex(card => card.id === this.currentCard.id);
                            if (cardIndex !== -1) {
                                const currentDate = new Date();
                                const year = currentDate.getFullYear();
                                const month = String(currentDate.getMonth() + 1).padStart(2, '0');
                                const day = String(currentDate.getDate()).padStart(2, '0');
                                const hours = String(currentDate.getHours()).padStart(2, '0');
                                const minutes = String(currentDate.getMinutes()).padStart(2, '0');
                                const seconds = String(currentDate.getSeconds()).padStart(2, '0');
                                const currentTime = new Date(new Date().getTime() + (8 * 60 * 60 * 1000)).toISOString().replace('T', ' ').substring(0, 19);
                                this.previewCards[cardIndex].back = backtextarea;
                                this.previewCards[cardIndex].front = fronttextarea;
                                this.previewCards[cardIndex].updatetime = currentTime;
                                this.savePreviewCardsToLocalStorage();
                                alert("更新完成");
                            } else alert("未找到要更新的卡片");


                        }).catch(error => {
                            console.error('在执行过程中出错:', error);
                        });



                        console.log('Found card details:', previewCards[cardIndex]);
                    } else {

                        //新增

                        if(!this.checkVip()){
                            alert("非会员只能创建20张自定义卡，请前往个人中心升级会员")
                            return;
                        }
                        this.EditOrAdd = 1

                        var fronttextarea = nodefront;

                        var backtextarea = "";
                        const cardIndex = this.previewCards.findIndex(card => card.front === fronttextarea);
                        if (cardIndex === -1) {
                            const currentDate = new Date();
                            const year = currentDate.getFullYear();
                            const month = String(currentDate.getMonth() + 1).padStart(2, '0');
                            const day = String(currentDate.getDate()).padStart(2, '0');
                            const hours = String(currentDate.getHours()).padStart(2, '0');
                            const minutes = String(currentDate.getMinutes()).padStart(2, '0');
                            const seconds = String(currentDate.getSeconds()).padStart(2, '0');
                            const currentTime = new Date(new Date().getTime() + (8 * 60 * 60 * 1000)).toISOString().replace('T', ' ').substring(0, 19);
                            var id = this.uid + new Date().getTime().toString();
                            const newCard = {
                                id: nodeid,
                                front: fronttextarea,
                                back: backtextarea,
                                time: currentTime,
                                updatetime: currentTime,
                                mark: 0
                            };
                            this.previewCards.unshift(newCard);
                            this.savePreviewCardsToLocalStorage();
                            alert("新增完成");

                            // console.log("同步到思维导图")
                            // let topicid = this.findTopicIdByCardId(id)
                            // //同步到思维导图
                            // this.addNewNodeToTopic({
                            //     text: fronttextarea.replace(/<\/?p>/g, ""),
                            //     id: id,
                            //     topicid: topicid,
                            //     fold: 0
                            // });

                            this.save_xinzengids(id)
                        } else alert("卡片名称冲突，重新命名");





                        console.log('Card not found');
                    }

                    this.mindcommonSave()



                }).catch((error) => {
                    console.error('初始化过程中发生错误:', error);
                });


            //    previewCards找到这个卡片的位置
                // 假设cardId是你要查找的卡片ID

            //

            }






            console.log("mindEditNode")
            return ;
            var self_ = this
            console.log("节点编辑")
            if(value.dataAfter==value.dataPre){
                return
            }
            console.log(value)

            // 调用修改的代码     json.front.split("：").length > 1?json.front.split("：")[1]:json.front.split(":")[1] dataTotal.nodeData.id
            var orderIndex = self_.orderActivities.findIndex(json => json.id==value.dataTotal.nodeData.id)
            if(orderIndex!=-1){

                self_.card = self_.orderActivities[orderIndex]
                self_.floatEdit = value.dataAfter

                self_.cardOprate.known = 0
                self_.oriCardTag=self_.oprateTag(self_.card)
                self_.cardOprate = JSON.parse(JSON.stringify(self_.card));
                self_.cardOprate.tag = self_.oprateTag(self_.card)
                self_.cardOprate.front = self_.floatEdit
                self_.cardOprate.back= self_.show
                self_.card.back= self_.show
                // save之后order没有变导致的问题
                self_.edit_save_card();
                /**
                 * save之后进行重置 front和back过程
                 */



            }else{
                console.log("无此节点")
            }


        },
        async mindAddNode(e){
            console.log("mindAddNode")
            this.mindcommonSave()
            return;
            var self = this
            console.log("节点新增1")
            console.log(e)

            /**
             * 这里tag使用思维导图的tag表示
             */
            self.cardOprate.tag = self.dynamicTags.join('-')
            self.cardOprate.front = e.data
            self.cardOprate.back = self.show
            self.cardOprate.known = 0
            self.cardOprate.eid = ""





            self.cardOprate.mindmapLayer=e.layer
            if(e.layer!=0){
                let leftIndex = this.orderActivities.findIndex(json => json.id==e.left)
                self.cardOprate.mindmapParentId=this.orderActivities[leftIndex].id

            }else{
                self.cardOprate.mindmapParentId = 0

            }
            /**
             * 除了top不一样，别的都一样。
             */
            if(e.top==""){
                // 表示是头节点，查询的时候刚开始就要插入，如果有两个头结点按照最新的插入
                self.cardOprate.listSameLevelId=-1
            }else{
                let topIndex = this.orderActivities.findIndex(json => json.id==e.top)
                self.cardOprate.mindmapSameLevelId=this.orderActivities[topIndex].id
                self.cardOprate.listSameLevelId=0
            }






            self.CardPostSubmit(self.cardOprate)

            //提交成功之后进行下一步的时候这时候进行更新操作
            self.updateMindMapRoot(e.node.root.children,e.data)


            // 添加成功之后将数据添加到activities中

            // self.orderActivities.push(jsonActivity1)
            // var objMind = JSON.parse(JSON.stringify(children))

        },
        mindmapupdate:function(value){
            console.log("mindmapupdate")
            return;
            console.log("监听到点击update事件发生")
            console.log(value)
        },

        // 点击保存按钮事件 // 递归保存变更层次的数据内容
        mindmapsavedata:function(value){
            console.log("mindmapsavedata")
            return;
            var self = this
            console.log("监听到点击savedate事件发生")
            console.log(value)
            var prepareListEditCard=[]
            var extractFromMindMap = []
            self.doLoop(extractFromMindMap,value.root.children,0,0)
            // 递归实现记录层号和传递数据到下一层
            self.orderActivities.map((a)=>{
                var testjump = extractFromMindMap.forEach(b=>{
                    if(a.id==b.id){
                        if(a.mindmapLayer!=b.mindmapLayer||a.mindmapParentId!=b.mindmapParentId){
                            prepareListEditCard.push(b)
                        }
                    }
                })
                console.log(testjump)
            })
            console.log(prepareListEditCard)
            // prepareListEditCard.map((json)=>{updateMindMap()})

            prepareListEditCard.forEach((c)=>{
                let index = self.orderActivities.findIndex(json => json.id == c.id)
                if(index!=-1){
                    self.orderActivities[index].mindmapLayer = c.mindmapLayer
                    self.orderActivities[index].mindmapParentId = c.mindmapParentId
                    self.editCard(self.orderActivities[index])
                    self.edit_save_card_ES_Only()
                }
            })
        },
        doLoop(extractFromMindMap,value,mindmapLayer,mindmapParentId){
            var self = this
            value.forEach((c)=>{
                c.data.mindmapParentId = mindmapParentId
                c.data.mindmapLayer = mindmapLayer
                extractFromMindMap.push(c.data)
                if(c.children.length>0){
                    self.doLoop(extractFromMindMap,c.children,mindmapLayer+1,c.data.id)
                }
            })
        },
// 点击节点事件
        mindmapnodeclick:function(value){
            console.log("mindmapnodeclick")


            let topicName =""


            let nodeid = value.data.id
            let topicid = value.data.topicid
            let nodefront = value.data.text
            let nodefold = value.data.fold === 'undefined' ? 0:value.data.fold
            //找到这个卡片，然后更新front值，就是将这个卡片信息带入到更新卡片中
            if(nodefold===0){

                topicName = this.getTopicNameById(topicid);
                console.log('Topic Name:', topicName);
                if(topicName===localStorage.getItem('dangqianzhuti')){

                }else{
                    //dangqianzhutititle
                    localStorage.setItem('dangqianzhuti',topicName)
                    localStorage.setItem('dangqianzhutititle',topicName)

                }
                // this.initmount(topicName)
                //切换主题
                this.initmount(topicName).then(() => {
                    const cardId = nodeid;

                    const previewCards = this.previewCards;
                    const cardIndex = previewCards.findIndex(card => card.id === cardId);
                    console.log('Card Index:', cardIndex);
                    if (cardIndex !== -1) {
                        // this.dianjishijianxian_kapian(cardIndex)
                        this.dianjishijianxian_kapian(cardIndex).then(result => {}).catch(error => {
                            console.error('在执行过程中出错:', error);
                        });



                        console.log('Found card details singlenode');
                    } else {


                        console.log('Card not found');
                    }



                }).catch((error) => {
                    console.error('初始化过程中发生错误:', error);
                });


                //    previewCards找到这个卡片的位置
                // 假设cardId是你要查找的卡片ID

                //

            }else{
                alert("这是目录不可修改")
            }







            console.log("mindEditNode")
            //添加之后进行转换吧，完成之后进行

            return ;
            var self_ = this
            console.log("节点编辑")
            if(value.dataAfter==value.dataPre){
                return
            }
            console.log(value)

            // 调用修改的代码     json.front.split("：").length > 1?json.front.split("：")[1]:json.front.split(":")[1] dataTotal.nodeData.id
            var orderIndex = self_.orderActivities.findIndex(json => json.id==value.dataTotal.nodeData.id)
            if(orderIndex!=-1){

                self_.card = self_.orderActivities[orderIndex]
                self_.floatEdit = value.dataAfter

                self_.cardOprate.known = 0
                self_.oriCardTag=self_.oprateTag(self_.card)
                self_.cardOprate = JSON.parse(JSON.stringify(self_.card));
                self_.cardOprate.tag = self_.oprateTag(self_.card)
                self_.cardOprate.front = self_.floatEdit
                self_.cardOprate.back= self_.show
                self_.card.back= self_.show
                // save之后order没有变导致的问题
                self_.edit_save_card();
                /**
                 * save之后进行重置 front和back过程
                 */



            }else{
                console.log("无此节点")
            }









            return;
            // // this.cancelMindShow = true
            // var self_ = this
            // console.log("监听到点击node事件发生")
            // console.log(value.data.text)
            // // 找到点击的card并变成当前card
            // var orderIndex = self_.orderActivities.findIndex(json => json.id==value.data.id)
            // if(orderIndex!=-1){
            //     this.card = this.orderActivities[orderIndex]
            // }
            // // this.timeline(value.data.text)
            // self_.show=this.card.back.replace(/<img /g,"<img preview style='object-fit:contain' ").replace(/https:\/\/gitee.com/gm,this.global_request_url.requestNodeLocal)
        },
        changeMindMap:function() {

            this.mindMapShow= !this.mindMapShow
            // 进行index提升和降落
            if(this.mindMapShow){
                this.simmindIndex = 0
            }else{
                this.simmindIndex = -1
            }
            this.btngroupShow=!this.btngroupShow

        },


        async headleSaveData() {
            let data = await this.$refs.test.getNowView();
            console.log(data);
            console.log(this.$refs.test.getNowView);
        },
        uploadImage(e) {
            // eslint-disable-next-line no-unused-vars
            return new Promise((reslove, reject) => {
                console.log(e);
                setTimeout(
                    reslove(
                        "https://blog.xkongkeji.com/static/img/cover1.fb9e08c.jpg"
                    ),
                    3000
                );
            });
        },

        getOrderFromZhuti(topicName) {
            // 从localStorage中获取zhuti数据
            const zhutiData = JSON.parse(localStorage.getItem('zhuti') || '{}');
            // 递归查找与topicName匹配的主题，并返回其order
            const findOrder = (topics) => {
                for (const topic of topics) {
                    if (topic.topicname === topicName && topic.order) {
                        return topic.order.split(',');
                    }
                    if (topic.children) {
                        const result = findOrder(topic.children);
                        if (result) return result;
                    }
                }
                return null;
            };
            return findOrder(zhutiData.topics || []);
        },
        mindMapShow(){
            Swal.fire({
                title: '内测中',
                text: '',
                icon: 'info',
                confirmButtonText: '好的'
            })

        },
        toggleMenu() {
            this.showMenuT = !this.showMenuT;  // 切换菜单的显示状态
        },
        async initmount(topicTitle) {
            try {
                localStorage.setItem("dangqianzhutititle", topicTitle);
                localStorage.setItem("dangqianzhuti", topicTitle);
                // localStorage.removeItem("cards");
                // localStorage.removeItem("zhuti");

                const uid = localStorage.getItem('uid');
                if (!uid) {
                    await Swal.fire({
                        title: '未登录',
                        text: '即将跳转登录页面，推荐使用微信扫码登录',
                        icon: 'info',
                        confirmButtonText: '好的'
                    });
                    window.location.href = '/loginorregistry'; // 这里的 '/login' 是你希望跳转到的URL
                    return; // Stop further execution in case of no UID
                }
                this.uid = uid;

                // Fetch data and initialize components
                // await this.fetchData1();
                // await this.fetchAndStoreZhuti1();
                await this.pageInit();

                // Sort preview cards after initialization
                await this.sortPreviewCards();
                this.ifbianjidonghua = false;

                const previewCards = JSON.parse(localStorage.getItem('previewCards') || '[]');
                if (previewCards.length > 0) {
                    this.ifbianji = false;
                } else {
                    localStorage.setItem('initTinyMCE', 'true');
                }

                // Hide loading animation
                const elements = document.querySelectorAll('.jiazaizhongbg');
                elements.forEach(element => element.style.display = 'none');

                console.log('Initialization completed successfully.');
            } catch (error) {
                console.error('Initialization failed:', error);
                throw error; // Re-throw error to be handled by .catch if needed
            }
        },
        displayNoneSjx(){
            if (document.getElementById('scrollContainer').style.display === 'flex') {
                // 修改display属性为none
                $('#closetimeline').trigger('click')
            }
        },
    searchCards(){},
    	  selectAll() {
      this.selectedCards = this.previewCards.map(card => card.id); // 将所有卡片的 ID 添加到 selectedCards 数组
    },
    deselectAll() {
      this.selectedCards = []; // 清空选中的卡片数组
    },
     selectMarked() {
      // 只选择那些 mark 属性为 1 的卡片
      this.selectedCards = this.previewCards.filter(card => card.mark === 1).map(card => card.id);
    },
    	toggleCheckboxes() {
      this.showCheckboxes = !this.showCheckboxes; // 切换显示状态
    },
        changeModeNormal(){
            // qiehuanfuximoshi
        //    zhengmiankaneirong
            if(document.getElementById('qiehuanfuximoshi').style.display === 'none'){
                document.getElementById('qiehuanfuximoshi').style.display = 'block'
                document.getElementById('zhengmiankaneirong').style.display = 'none'
            }else{
                document.getElementById('qiehuanfuximoshi').style.display = 'none'
                document.getElementById('zhengmiankaneirong').style.display = 'flex'
            }


        },
        allStarquxiao(){
        //    将所有卡片的known状态重置为0
            alert("当前暂不可取消，如有需要可以联系客服，后台操作")
        },
        checkjihuo(){
            var checkbox = document.getElementById('jihuo');
// 检查 checkbox 是否被选中
            if (checkbox.checked) {
                console.log('Checkbox is checked');
                this.checkjihuo = true;
            } else {
                console.log('Checkbox is unchecked');
                this.checkjihuo = false;
            }
        },
        checktuozhuai(){
            var checkbox = document.getElementById('tuozhuaijihuo');
            if(checkbox!==null){
                if (checkbox.checked) {
                    console.log('Checkbox is checked');
                    this.checkjihuo = true
                    // 执行其他操作
                } else {
                    console.log('Checkbox is not checked');
                    this.checkjihuo = false
                }

            }

        },
        // 用于从URL加载图片并转换为Base64编码
        getImageBase64(url, callback) {
            var img = new Image();
            img.crossOrigin = 'Anonymous'; // 处理跨域问题
            img.onload = function () {
                var canvas = document.createElement("canvas");
                canvas.width = this.naturalWidth;
                canvas.height = this.naturalHeight;
                var ctx = canvas.getContext("2d");
                ctx.drawImage(this, 0, 0);
                var dataURL = canvas.toDataURL("image/png");
                callback(dataURL);
            };
            img.onerror = function() {
                console.error('Cannot load image from URL: ' + url);
                callback(null);
            };
            img.src = url;
        },

// 从文本中提取URL并生成PDF
        // 从文本中提取URL并生成PDF

        generatePDFWithImagesFromText(docDefinition, text, headstyle) {
            return new Promise((resolve, reject) => {

                const regex = /https?:\/\/\S+\.(jpg|jpeg|png|gif)/gi;
                let urls = text.match(regex) || [];

                let imagePromises = urls.map(url => {
                    return new Promise((resolve, reject) => {
                        this.getImageBase64(url, base64Image => {
                            if (base64Image) {
                                resolve({
                                    image: base64Image,
                                    width: 150,
                                    alignment: 'center'
                                });
                            } else {
                                reject(new Error(`Failed to convert image from URL: ${url}`));
                            }
                        });
                    });
                });

                Promise.all(imagePromises).then(images => {
                    let lastIndex = 0;
                    images.forEach((imageObj, index) => {
                        let imagePosition = text.indexOf(urls[index], lastIndex); // <img src=" &nbsp;
                        let textBeforeImage = text.substring(lastIndex, imagePosition).replaceAll('<p><img src="',"").replaceAll('" /></p>',"").replaceAll("<p>","").replaceAll("</p>","").replaceAll('&nbsp;',"").replaceAll('<img src="',"");
                        if (textBeforeImage) {
                            docDefinition.content.push({text: headstyle==='per_info_header'?this.globalOrder+"、"+textBeforeImage:textBeforeImage, style:headstyle});
                            this.pdfHtmlString=this.pdfHtmlString+text.substring(lastIndex, imagePosition)
                        }
                        docDefinition.content.push(imageObj);

                        if(this.pdfHtmlString.endsWith('src="')){
                            this.pdfHtmlString=this.pdfHtmlString + imageObj.image
                        }else{
                            this.pdfHtmlString=this.pdfHtmlString + `<img src="${imageObj.image}" >`;
                        }
                            // + " " + imageObj.image
                        lastIndex = imagePosition + urls[index].length;
                    });

                    if (lastIndex < text.length && images.length>0) {
                        docDefinition.content.push({text: text.substring(lastIndex).replaceAll('<p><img src="',"").replaceAll('" /></p>',"").replaceAll("<p>","").replaceAll("</p>","").replaceAll('&nbsp;',"").replaceAll('<img src="',""), style:headstyle});
                        this.pdfHtmlString = this.pdfHtmlString + text.substring(lastIndex)
                        docDefinition.content.push('\n')
                    }

                    resolve();
                }).catch(error => {
                    console.error('Error creating PDF:', error);
                    reject(error);
                });

                if (urls.length === 0) {
                    text = headstyle==='per_info_header'?this.globalOrder+"、"+text:text
                    docDefinition.content.push({text: text.replaceAll('<p><img src="',"").replaceAll('" /></p>',"").replaceAll("<p>","").replaceAll("</p>","").replaceAll('&nbsp;',"").replaceAll('<img src="',""), style:headstyle});
                    this.pdfHtmlString = this.pdfHtmlString + text
                    docDefinition.content.push('\n')
                    resolve();
                }
            });
        },

// 示例文本


        openModal() {

            this.generateAndPreviewPDF();
        },
        closeModal() {
            this.pdfUrl = null; // 清除PDF URL
        },
        async generateAndPreviewPDF() {
            // pdfMake.vfs = pdfFonts.pdfMake.vfs;
            pdfMake.fonts = {
                Roboto: {
                    normal: '方正黑体简体.TTF',
                    bold: '方正黑体简体.TTF',
                    italics: '方正黑体简体.TTF',
                    bolditalics: '方正黑体简体.TTF'
                },
                msyh: {
                    normal: '方正黑体简体.TTF',
                    bold: '方正黑体简体.TTF',
                    italics: '方正黑体简体.TTF',
                    bolditalics: '方正黑体简体.TTF',
                }
            };
            var docDefinition = {
                pageSize: 'A4',
                content: [],
                defaultStyle: {
                    font: 'msyh' // 确保你已经将 'msyh' 字体添加到 pdfMake 的 VFS 中，并正确配置了字体
                },
                styles: {
                    per_info_header: {
                        fontSize: 15,
                        alignment: 'left',
                        bold: true
                    },
                    per_info: {

                    }
                }
            };
            // docDefinition.content.push({ toc: { title: { text: '目录', style: 'per_info_header' }, numberStyle: { bold: true } } })

            this.globalOrder = 0
            //修改为 使用cards中的进行渲染的过程 过滤掉
            this.pdfHtmlString= ""
            let cards =  this.previewCards.filter(card => this.selectedCards.includes(card.id));
            for (const card of cards) {
                this.globalOrder = this.globalOrder+1
                await this.generatePDFWithImagesFromText(docDefinition,card.front,'per_info_header');
                await this.generatePDFWithImagesFromText(docDefinition,card.back,'per_info');
            }

             // console.log(this.pdfHtmlString)

            // 生成PDF
            const options = {
                margin: 10, // 设置页面边距
                jsPDF: {
                    unit: 'mm',
                    format: 'a4'
                }
            };

            try {
                const blob = await html2pdf().set(options).from(this.pdfHtmlString).output('blob').catch(error => {
                    console.error('Capture failed', error);
                });;
                this.pdfUrl = URL.createObjectURL(blob);
                console.log(this.pdfUrl);
                // 可以在这里添加iframe预览代码或其他处理
            } catch (error) {
                console.error('生成PDF失败:', error);
            }


        // document.getElementById('exportword').addEventListener('click', generateAndPreviewPDF1);
            return;

            // 创建PDF并获取为Blob
            pdfMake.createPdf(docDefinition).getBuffer((buffer) => {
                const blob = new Blob([buffer], { type: 'application/pdf' });
                // 创建Blob URL
                this.pdfUrl = URL.createObjectURL(blob);
                // this.showModal = true;
            });
        },

                    exportCardsToPDF() {
                const docDefinition = {
                    content: [
                        { text: 'Hello World', style: 'header' },
                        'This is an example PDF generated with pdfMake'
                    ],
                    styles: {
                        header: {
                            fontSize: 18,
                            bold: true,
                            margin: [0, 0, 0, 10]
                        },
                        subheader: {
                            fontSize: 16,
                            bold: true,
                            margin: [0, 10, 0, 5]
                        },
                        tableExample: {
                            margin: [0, 5, 0, 15]
                        },
                        tableHeader: {
                            bold: true,
                            fontSize: 13,
                            color: 'black'
                        }
                    }
                };

                // 创建PDF并获取为Blob
                pdfMake.createPdf(docDefinition).getBuffer((buffer) => {
                    const blob = new Blob([buffer], { type: 'application/pdf' });
                    // 创建Blob URL
                    this.pdfUrl = URL.createObjectURL(blob);
                });
    },


        exportCardsToPDF1(){
            const docDefinition = {
                content: [
                    { text: 'This is a header', style: 'header' },
                    'No styling here, this is a standard paragraph',
                    { text: 'Another text', style: 'anotherStyle' },
                    { text: 'Multiple styles applied', style: ['header', 'anotherStyle'] }
                ],
                styles: {
                    header: {
                        fontSize: 22,
                        bold: true
                    },
                    anotherStyle: {
                        fontSize: 16,
                        italics: true,
                        alignment: 'right'
                    }
                }
            };

            // 创建PDF并下载
            pdfMake.createPdf(docDefinition).download();
        }
,
        deleteCardPreview(cardToDelete) {
            this.ifpiliangdianjiShanChu = true
            // 使用 filter 方法从 previewCards 数组中移除相应的卡片
            this.previewCards = this.previewCards.filter(card => card.id !== cardToDelete.id);
            //
            this.piliangdianjiCard = cardToDelete

            this.savePreviewCardsToLocalStorage()

            let shanchu = localStorage.getItem('shanchu') ? JSON.parse(localStorage.getItem('shanchu')) : [];
            shanchu.push(cardToDelete.id);
            localStorage.setItem('shanchu', JSON.stringify(shanchu));
        },
        cancelCard(cardToEdit) {

            if (cardToEdit.front.trim() === '' && cardToEdit.back.trim() === '') {
                // 如果 front 和 back 都为空，则删除该卡片
                this.previewCards = this.previewCards.filter(card => card.id !== cardToEdit.id);
            } else {
                // 如果不是，则仅停止编辑模式
                this.previewCards = this.previewCards.map(card =>
                    card.id === cardToEdit.id ? { ...card, isEditing: false } : card
                );
            }


            tinymce.remove('#front-editor-' + cardToEdit.id);
            tinymce.remove('#back-editor-' + cardToEdit.id);
        },
        editCard(cardToEdit) {

            this.currentCardIndex = this.previewCards.findIndex(c => c.id === cardToEdit.id);
            this.previewCards = this.previewCards.map(card =>
                card.id === cardToEdit.id ? { ...card, isEditing: true } : card
            );

            this.$nextTick(() => {
                // 对前面的编辑器进行初始化
                tinymcechushihuamyTextarea('#front-editor-' + cardToEdit.id,4)
                tinymcechushihuamyTextarea('#back-editor-' + cardToEdit.id,4)

            });
        },
        saveCard(cardToSave) {
            const currentDate = new Date();
            const year = currentDate.getFullYear();
            const month = String(currentDate.getMonth() + 1).padStart(2, '0');
            const day = String(currentDate.getDate()).padStart(2, '0');
            const hours = String(currentDate.getHours()).padStart(2, '0');
            const minutes = String(currentDate.getMinutes()).padStart(2, '0');
            const seconds = String(currentDate.getSeconds()).padStart(2, '0');
            const currentTime = new Date(new Date().getTime() + (8 * 60 * 60 * 1000)).toISOString().replace('T', ' ').substring(0, 19);;


            this.ifpiliangdianjiCard = true
            // 假设每个卡片编辑器的id遵循一定的命名规则
            const frontEditorId = 'front-editor-' + cardToSave.id;
            const backEditorId = 'back-editor-' + cardToSave.id;

            // 直接从tinymce实例获取内容
            const frontContent = tinymce.get(frontEditorId).getContent();
            const backContent = tinymce.get(backEditorId).getContent();

            // 如果front没值则不能保存
            if(frontContent===""){
                alert("卡片正面内容不能为空")
                return;
            }
            // 更新当前卡片数据
            cardToSave.updatetime = currentTime
            cardToSave.front = frontContent;
            cardToSave.back = backContent;
            cardToSave.isEditing = false;
            console.log("🚀 ~ file: perform-vue.js ~ line 120 ~ cardToSave: ",cardToSave);
            // 这里您可以添加保存到后端的代码
            tinymce.remove('#front-editor-' + cardToSave.id);
            tinymce.remove('#back-editor-' + cardToSave.id);
            cardToSave.id
            //根据id从previewCards中找到对应卡片
            const cardIndex = this.previewCards.findIndex(card => card.id === cardToSave.id);
            if (cardIndex !== -1) {
                this.piliangdianjiCard = this.previewCards[cardIndex];
            }else{
                alert("没有找到对应卡片")
                return;
            }
            //更新卡片数据
            this.savePreviewCardsToLocalStorage()
        },
        addCard(card) {
            // 处理新增卡片逻辑
            const currentDate = new Date();
            const year = currentDate.getFullYear();
            const month = String(currentDate.getMonth() + 1).padStart(2, '0');
            const day = String(currentDate.getDate()).padStart(2, '0');
            const hours = String(currentDate.getHours()).padStart(2, '0');
            const minutes = String(currentDate.getMinutes()).padStart(2, '0');
            const seconds = String(currentDate.getSeconds()).padStart(2, '0');
            const currentTime = new Date(new Date().getTime() + (8 * 60 * 60 * 1000)).toISOString().replace('T', ' ').substring(0, 19);;
            var id = this.uid + new Date().getTime().toString();
            //找到点击的卡片的主题名
            const cards = JSON.parse(localStorage.getItem('cards')) || {};
            let foundThemeName = null;

            // 遍历cards中的每个主题
            Object.keys(cards).forEach(themeName => {
                if(themeName==="所有卡片"){
                    return;
                }
                const themeCards = cards[themeName].previewCards || [];
                // 查找匹配的卡片
                const found = themeCards.some(themeCard => themeCard.id === card.id);
                if (found) {
                    // 找到后，保存主题名称
                    foundThemeName = themeName;
                    return;
                }
            });


            const newCard = {
                id: id,
                front: '',
                back: '',
                time: currentTime,
                updatetime: currentTime,
                mark: 0,
                isEditing:true,
                topicname:foundThemeName

            };
            // 获取当前卡片的索引
            const index = this.previewCards.findIndex(c => c.id === card.id);

            // 在当前卡片的下一个位置插入新卡片
            if (index >= 0) {
                this.previewCards.splice(index + 1, 0, newCard);
            } else {
                // 如果没有提供当前卡片（比如列表为空），则添加到末尾
                this.previewCards.push(newCard);
            }

            this.$nextTick(() => {
                // 对前面的编辑器进行初始化
                tinymcechushihuamyTextarea('#front-editor-' + newCard.id,4)
                tinymcechushihuamyTextarea('#back-editor-' + newCard.id,4)

            });


        },
        getNextId() {
            // 生成一个新的ID
            return new Date().toISOString().slice(0, 19).replace('T', ' ');
        },
        toggleModal() {


        		this.selectAll()
            this.zhengmianbeimianshow = false
            if(document.getElementById('piliangbianjikuang').style.display === 'none'||document.getElementById('piliangbianjikuang').style.display === ''){
                document.getElementById('piliangbianjikuang').style.display = 'flex';
            }else{
                document.getElementById('piliangbianjikuang').style.display = 'none';
            }
        },
        // 更新主题下的特定卡片 所有卡片模式下
        updateCardInCards(cards) {
            // 从localStorage获取cards数据
            if(this.ifpiliangdianjiCard){
                const {  id } = this.piliangdianjiCard;
                const topicname = this.piliangdianjiCard.topicname
                // 检查是否存在对应主题和卡片
                if (cards[topicname] && cards[topicname].previewCards) {
                    // 在对应主题下找到匹配ID的卡片
                    let cardIndex = cards[topicname].previewCards.findIndex(card => card.id === id);

                    // 如果找到，更新该卡片
                    if (cardIndex !== -1 && this.EditOrAdd === 0) {
                        cards[topicname].previewCards[cardIndex] = { ...this.piliangdianjiCard };
                        console.log(`Card with id ${id} updated in topic ${topicname}.`);

                        // 将更新后的cards数据保存回localStorage
                        // localStorage.setItem('cards', JSON.stringify(cards));
                    } else {
                        cards[topicname].previewCards.unshift(this.piliangdianjiCard)
                        console.log(`Card with id ${id} not found in topic ${topicname}.`);
                    }
                } else {
                    console.log(`Topic ${topicname} not found.`);
                }

            }else if(this.ifpiliangdianjiShanChu){

                // this.piliangdianjiCard.forEach(cardToDelete => {
                const { id, topicname } = this.piliangdianjiCard;
                // 检查是否存在对应主题和卡片
                if (cards[topicname] && cards[topicname].previewCards) {
                    // 过滤掉要删除的卡片
                    cards[topicname].previewCards = cards[topicname].previewCards.filter(card => card.id !== id);
                    console.log(`Card with id ${id} deleted from topic ${topicname}.`);
                } else {
                    console.log(`Topic ${topicname} not found or does not contain the card with id ${id}.`);
                }
                // });
                // 重置批量删除标志
                // this.ifpiliangdianjiShanChu = false;
            }
            else{

                // 获取当前卡片的主题名称和ID,新增的时候
                const {  id } = this.currentCard;
                const topicname = this.dangqianzhutititle
                // 检查是否存在对应主题和卡片
                if (cards[topicname] && cards[topicname].previewCards) {
                    // 在对应主题下找到匹配ID的卡片
                    let cardIndex = cards[topicname].previewCards.findIndex(card => card.id === id);

                    // 如果找到，更新该卡片
                    if (cardIndex !== -1 && this.EditOrAdd === 0) {
                        cards[topicname].previewCards[cardIndex] = { ...this.currentCard };
                        console.log(`Card with id ${id} updated in topic ${topicname}.`);

                        // 将更新后的cards数据保存回localStorage
                        // localStorage.setItem('cards', JSON.stringify(cards));
                    } else {
                        cards[topicname].previewCards.unshift(this.previewCards[0])
                        console.log(`Card with id ${id} not found in topic ${topicname}.`);
                    }
                } else {
                    console.log(`Topic ${topicname} not found.`);
                }

            }

        },
        updateCurrentThemeByCard() {
            const currentCard = this.currentCardWithTheme;
            if (!currentCard) return;

            // Assuming each card has a 'theme' property linking to its theme
            const cardTheme = currentCard.cardTheme;
            console.log("🚀 ~ file: perform-vue.js ~ line 68 ~ cardTheme: ",cardTheme);

            if (cardTheme) {
                this.dangqianzhuti = cardTheme;
            } else {
                // Handle case where card's theme is not found
                console.error("Current card's theme is not defined.");
            }
        },
        refreshBack(){
            this.$previewRefresh();
        },
        focusSearch() {
            document.getElementById('scrollContainer').style.display = 'flex';
        },
        shijianxiandragEnd() {
            console.log("==========shijianxiandragEnd=========")
            this.savePreviewCardsToLocalStorage();
        },
        toggleStarredMode() {
            this.onlyStarred = !this.onlyStarred;
        },
        toggleRandomMode() {
            this.isRandomMode = !this.isRandomMode;
        },
        stopAutoPlay() {
            if (this.autoPlayTimer) {
                clearInterval(this.autoPlayTimer);
                this.autoPlayTimer = null;
            }
        },
        zidongbofangliucheng() {
            $('#zhengmiankaneirong').trigger('click');
            // fanhuizhengmian  $('#fanhuizhengmian').trigger('click');
            this.stopAutoPlay()
            this.autoPlayTimer = setInterval(() => {
                if(document.getElementById("kapianzhengmian").style.display==='none'){
                //     这是反面
                    $('#xiayizhangka').trigger('click');

                }else{
                    // 这是正面，返回反面
                    $('#zhengmiankaneirong').trigger('click');
                }
            }, 10000);
        },
        startAutoPlay() {
            this.stopAutoPlay();
            setTimeout(this.zidongbofangliucheng, 10000);
        },
        shoucangkapian() {
            this.currentCard.mark = 1;
            this.currentCard.updatetime = new Date(new Date().getTime() + (8 * 60 * 60 * 1000)).toISOString().replace('T', ' ').substring(0, 19);
            console.log("🚀 ~ file: cardperform.html ~ line 370 ~ this.currentCard.updatetime: ", this.currentCard.updatetime);
            this.savePreviewCardsToLocalStorage();
        },
        quxiaoshoucangkapian() {
            this.currentCard.mark = 0;
            this.currentCard.updatetime = new Date(new Date().getTime() + (8 * 60 * 60 * 1000)).toISOString().replace('T', ' ').substring(0, 19);
            this.savePreviewCardsToLocalStorage();
        },
        triggerScrollToActive() {
            this.displayNoneSjx()
            this.zhengmianbeimianshow = false
            setTimeout(() => {
                this.scrollToActive();
            }, 500);
        },
        scrollToActive() {
            const container = document.getElementById('scrollContainer');
            const activeElements = document.querySelectorAll('.active-background');
            const activeElement = activeElements[activeElements.length - 1];
            if (activeElement) {
                const containerHeight = container.clientHeight;
                const elementTop = activeElement.offsetTop;
                const elementHeight = activeElement.clientHeight;
                const scrollTop = elementTop + elementHeight / 2 - containerHeight / 2;
                container.scrollTop = scrollTop;
            }
        },
        setActiveIndex(index) {
            this.activeIndex = index;
            this.$nextTick(() => {
                this.scrollToActive();
            });
        },
        fanhuishangyiye() {
            window.history.back()
        },
        gengxinfuwenben() {
            this.zhongjianka = this.currentCard;
            const externalEditor = this.$refs.fuwenbenbianji;
            tinymce.get(externalEditor.id).setContent(this.zhongjianka.back);
        },
        shijianxianjiantou(index) {

            this.previewCards[index].icon = "el-icon-right";
            this.previewCards[index].size = "large";
            if(this.previewCards[this.currentIndex]){
                this.previewCards[this.currentIndex].icon = '';
                this.previewCards[this.currentIndex].size = 'normal';
            }

            this.setActiveIndex(index);
        },
        dianjishijianxian_kapian(index) {
            return new Promise((resolve, reject) => {
                try {
                    this.shijianxianjiantou(index);
                    this.currentIndex = index;
                    this.gengxinfuwenben();
                    this.dangqianzhutititle = this.currentCardWithTheme.cardTheme;

                    if (this.searchQuery === "") {
                        this.searchQuery = " ";
                    } else {
                        this.searchQuery = "";
                    }

                    resolve("操作成功完成");
                } catch (error) {
                    reject(error);
                }
            });
        },
        existsStarredCard() {
            return this.previewCards.some(card => card.mark === 1);
        },
        goToNextCard() {

            if (this.onlyStarred && !this.existsStarredCard()) {
                alert("没有星号卡片可显示");
                return;
            }

            let nextIndex = -1;
            if (this.isRandomMode) {
                // 随机模式逻辑
                if (this.onlyStarred) {
                    const starredCards = this.previewCards.filter(card => card.mark === 1);
                    if (starredCards.length > 0) {
                        const randomIndex = Math.floor(Math.random() * starredCards.length);
                        nextIndex = this.previewCards.indexOf(starredCards[randomIndex]);
                    }
                } else {
                    nextIndex = Math.floor(Math.random() * this.previewCards.length);
                }
            } else {
                // 顺序模式逻辑
                if (this.onlyStarred) {
                    for (let i = this.currentIndex + 1; i < this.previewCards.length; i++) {
                        if (this.previewCards[i].mark === 1) {
                            nextIndex = i;
                            break;
                        }
                    }
                    if (nextIndex === -1) {
                        for (let i = 0; i <= this.currentIndex; i++) {
                            if (this.previewCards[i].mark === 1) {
                                nextIndex = i;
                                break;
                            }
                        }
                    }
                } else {
                    nextIndex = (this.currentIndex + 1) % this.previewCards.length;
                }
            }
            if (nextIndex !== -1) {
                this.dianjishijianxian_kapian(nextIndex);
                this.currentIndex = nextIndex;
                this.gengxinfuwenben();
            }
            this.updateCurrentTopicByCardId(this.currentCard.id);
            this.updateCurrentThemeByCard()
        //    保存到localstorage提供给chatgpt
            localStorage.setItem('currentCard',JSON.stringify(this.currentCard))
            localStorage.setItem('currentIndex',this.currentIndex)
        },

        goToPreviousCard() {
            if (this.onlyStarred && !this.existsStarredCard()) {
                alert("没有星号卡片可显示");
                return;
            }

            let previousIndex = -1;
            if (this.isRandomMode) {
                // 随机模式逻辑
                if (this.onlyStarred) {
                    const starredCards = this.previewCards.filter(card => card.mark === 1);
                    if (starredCards.length > 0) {
                        const randomIndex = Math.floor(Math.random() * starredCards.length);
                        previousIndex = this.previewCards.indexOf(starredCards[randomIndex]);
                    }
                } else {
                    previousIndex = Math.floor(Math.random() * this.previewCards.length);
                }
            } else {
                // 顺序模式逻辑
                if (this.onlyStarred) {
                    for (let i = this.currentIndex - 1; i >= 0; i--) {
                        if (this.previewCards[i].mark === 1) {
                            previousIndex = i;
                            break;
                        }
                    }
                    if (previousIndex === -1) {
                        for (let i = this.previewCards.length - 1; i >= this.currentIndex; i--) {
                            if (this.previewCards[i].mark === 1) {
                                previousIndex = i;
                                break;
                            }
                        }
                    }
                } else {
                    previousIndex = this.currentIndex - 1 >= 0 ? this.currentIndex - 1 : this.previewCards.length - 1;
                }
            }

            if (previousIndex !== -1) {
                this.dianjishijianxian_kapian(previousIndex);
                this.currentIndex = previousIndex;
                this.gengxinfuwenben();
            }

            this.updateCurrentTopicByCardId(this.currentCard.id);
            this.updateCurrentThemeByCard()
        //    保存到localstorage提供给chatgpt
            localStorage.setItem('currentCard',JSON.stringify(this.currentCard))
            localStorage.setItem('currentIndex',this.currentIndex)
        },
        toggleMark(cardId) {
            const index = this.previewCards.findIndex(item => item.id === cardId);
            if (index !== -1) {
                this.previewCards[index].mark = !this.previewCards[index].mark;
            }
            localStorage.setItem('previewCards', JSON.stringify(this.previewCards));
        },
        removeCardIdFromLocalStorage(cardId) {
            // 从 localStorage 中获取名为 'xingzengids' 的字符串数组
            let xingzengids = localStorage.getItem('xinzengids');

            // 如果存在，则解析成数组
            if (xingzengids) {
                let idArray = JSON.parse(xingzengids);

                // 检查数组中是否包含指定的 cardId 字符串
                const index = idArray.indexOf(cardId);
                if (index !== -1) {
                    // 移除指定的字符串
                    idArray.splice(index, 1);

                    // 将更新后的数组保存回 localStorage
                    localStorage.setItem('xinzengids', JSON.stringify(idArray));
                }
            }
        }
        ,
deleteCard(cardId) {

            const index = this.previewCards.findIndex(card => card.id === cardId);
            if(index!==0){
                this.goToPreviousCard();
            }
            if (index !== -1) {
                this.previewCards.splice(index, 1);
                this.savePreviewCardsToLocalStorage();
            }
            let shanchu = localStorage.getItem('shanchu') ? JSON.parse(localStorage.getItem('shanchu')) : [];

            this.removeCardIdFromLocalStorage(cardId)
            shanchu.push(cardId);
            localStorage.setItem('shanchu', JSON.stringify(shanchu));
        //    删除之后更新思维导图
            this.deleteNodeAndPromoteChildren({
                text: "删除通用",
                id: cardId,
                topicid: "删除通用",
                fold: 0
            });


        },
        savePreviewCardsToLocalStorage() {
            if (this.previewCards.length === 0) {
                localStorage.removeItem('previewCards');
            } else {
                localStorage.setItem('previewCards', JSON.stringify(this.previewCards));
                this.saveToCenter()
            }
        },
        saveTopicNameToCards(cards){
            Object.keys(cards).forEach(topicName => {
                if(topicName==='所有卡片')return;
                if(cards[topicName].previewCards===undefined)return;
                cards[topicName].previewCards.forEach(card => {
                    card.topicname = topicName; // 给卡片添加所属主题名称
                });
            });
        },
        isCardIdInLocalStorage(cardId) {
            // 从 localStorage 中获取名为 'shanchu' 的字符串数组
            let shanchu = localStorage.getItem('shanchu');

            // 如果存在，则解析成数组
            if (shanchu) {
                let idArray = JSON.parse(shanchu);

                // 检查数组中是否包含指定的 cardId 字符串
                return idArray.includes(cardId);
            }

            // 如果 'shanchu' 不存在，返回 false
            return false;
        },
        saveToCenter() {
            let topic = {order: '', previewCards: []};
            topic.previewCards = [...this.previewCards];
            //filteredCards的order顺序
            topic.order = this.filteredCards.map(card => card.id).join(',');

            let cards = localStorage.getItem('cards') ? JSON.parse(localStorage.getItem('cards')) : {};
            this.saveTopicNameToCards(cards)
            if(localStorage.getItem("dangqianzhuti")==='所有卡片'){
                cards["所有卡片"] = topic
                this.updateCardInCards(cards)

            }else{
                cards[this.dangqianzhuti] = topic;
            }

            localStorage.setItem('cards', JSON.stringify(cards));
            localStorage.setItem('maxEditTimeZhuti', 0);
            const cards1 = JSON.parse(localStorage.getItem('cards'));
            if (cards1 && typeof cards1 === 'object') {
                let latestUpdateTime = new Date(0); // 设置初始最早的时间
                let latestCardId = null;
                Object.keys(cards1).forEach(key => {
                    let card = cards1[key];
                    //如果card下的previewCards不存在
                    if(card.previewCards!==undefined){
                        card.previewCards.forEach(previewCard => {
                            if ('front' in previewCard) previewCard.front = key + '：' + previewCard.front;
                            ;
                            if ('mark' in previewCard) {
                                previewCard.known = previewCard.mark;
                                delete previewCard.mark;
                            }
                            ;
                            if ('id' in previewCard) {
                                previewCard.sqlId = previewCard.id;
                                delete previewCard.id;
                            }
                            ;
                            if ('time' in previewCard) {
                                previewCard.createtime = previewCard.time;
                                delete previewCard.time;
                            }
                            ;
                            if ('updatetime' in previewCard) {
                                previewCard.lastmodifieddate = previewCard.updatetime;
                                delete previewCard.updatetime;
                                delete previewCard.icon;
                                delete previewCard.size;
                            }
                            ;previewCard.uid = this.uid;
                            previewCard.type = 1;


                            // 更新最近修改的卡片ID
                            const currentUpdateTime = new Date(previewCard.lastmodifieddate);
                            if (currentUpdateTime > latestUpdateTime) {
                                latestUpdateTime = currentUpdateTime;
                                latestCardId = previewCard.sqlId;
                            }
                        });
                    }
                });
                console.log("🚀 ~ file: cardperform.html ~ line 428 ~ latestCardId: ", latestCardId);
                if(!this.ifpiliangdianjiShanChu){

                    //如果这个在删除里有了就不新增了
                    if(!this.isCardIdInLocalStorage()){

                        this.save_xinzengids(latestCardId)
                    }
                }
                localStorage.setItem('cards2es', JSON.stringify(cards1))
            }

            //改变order
            this.saveToCenterZhutiXiugai();
            //兼容点击批量卡片的保存方式
            this.ifpiliangdianjiCard = false
            this.ifpiliangdianjiShanChu = false
        },
        saveToCenterZhutiXiugai() {
            let zhuti = localStorage.getItem('zhuti') ? JSON.parse(localStorage.getItem('zhuti')) : {};
            const dangqianzhuti = localStorage.getItem('dangqianzhuti');
            const newOrder = this.previewCards.map(card => card.id).join(',');
            const newOrderName = this.previewCards.map(card => card.front).join(',').replace(/<\/?p>/g, "");
            // const newTopicId = this.previewCards.map(card => card.topicname).join(',')

            if (zhuti && zhuti.topics) {
                const updateOrderAndEditTime = (topics) => {
                    topics.forEach(topic => {
                        if (topic.topictitle === dangqianzhuti) {
                            topic.order = newOrder;
                            topic.newOrderName = newOrderName;
                            topic.edittime = new Date().toISOString().slice(0, 19).replace('T', ' ');

                            if (topic.children && topic.children.length > 0) {
                                updateOrderAndEditTime(topic.children); // 递归处理子节点
                            }
                        } else if (topic.children && topic.children.length > 0) {
                            updateOrderAndEditTime(topic.children); // 递归处理其他层级
                        }
                    });
                };

                updateOrderAndEditTime(zhuti.topics);
                localStorage.setItem('zhuti', JSON.stringify(zhuti));
            }

        },
        getContentFromEditor() {
            this.EditOrAdd = 0
            var textarea = document.getElementById('fronttextarea');
            var fronttextarea = textarea.value;
            var editor = tinymce.get('myTextarea');
            var backtextarea = editor.getContent();
            const cardIndex = this.previewCards.findIndex(card => card.id === this.currentCard.id);
            if (cardIndex !== -1) {
                const currentDate = new Date();
                const year = currentDate.getFullYear();
                const month = String(currentDate.getMonth() + 1).padStart(2, '0');
                const day = String(currentDate.getDate()).padStart(2, '0');
                const hours = String(currentDate.getHours()).padStart(2, '0');
                const minutes = String(currentDate.getMinutes()).padStart(2, '0');
                const seconds = String(currentDate.getSeconds()).padStart(2, '0');
                const currentTime = new Date(new Date().getTime() + (8 * 60 * 60 * 1000)).toISOString().replace('T', ' ').substring(0, 19);
                this.previewCards[cardIndex].back = backtextarea;
                this.previewCards[cardIndex].front = fronttextarea;
                this.previewCards[cardIndex].updatetime = currentTime;
                this.savePreviewCardsToLocalStorage();
                alert("更新完成");
            } else alert("未找到要更新的卡片");
        },
        checkVip(){
            // 获取当前日期
            const currentDate = new Date();

// 从 localStorage 中获取 'zhuti' 数据
            const zhutiData = localStorage.getItem('zhuti');
            if (zhutiData) {
                const zhuti = JSON.parse(zhutiData);
                const vipDate = zhuti.vipdate ? new Date(zhuti.vipdate) : new Date(new Date().setDate(currentDate.getDate() - 1));

                // 检查当前日期是否大于 vipdate
                if (currentDate > vipDate) {
                    // 从 localStorage 获取 'cards' 数据
                    const cardsData = localStorage.getItem('cards');
                    if (cardsData) {
                        const cards = JSON.parse(cardsData);

                        // 检查是否存在键为 '所有卡片' 的数组
                        if (cards['所有卡片']) {
                            const allCardsLength = cards['所有卡片'].previewCards.length;
                            console.log('所有卡片的数组长度:', allCardsLength);
                            if (allCardsLength > 20) {
                                console.log('所有卡片的数组长度大于20，不能继续执行。');
                                return false; // 使用 return 中断执行
                            }
                            // 在这里执行提交逻辑
                            // 例如，可以是发送数据到服务器或者其他处理
                            // ...
                        } else {
                            console.log('没有找到键为‘所有卡片’的数组');
                        }
                    } else {
                        console.log('无法找到 cards 数据');
                    }
                } else {
                    console.log('当前日期不大于 VIP 日期');
                }
            } else {
                console.log('无法找到 zhuti 数据');
            }
            return true
        },
        getContentFromEditorXinZeng() {
            if(!this.checkVip()){
                alert("非会员只能创建20张自定义卡，请前往个人中心升级会员")
                return;
            }
            this.EditOrAdd = 1
            var textarea = document.getElementById('fronttextareaxinzeng');
            var fronttextarea = textarea.value;
            var editor = tinymce.get('myTextareaxinzeng');
            var backtextarea = editor.getContent();
            const cardIndex = this.previewCards.findIndex(card => card.front === fronttextarea);
            if (cardIndex === -1) {
                const currentDate = new Date();
                const year = currentDate.getFullYear();
                const month = String(currentDate.getMonth() + 1).padStart(2, '0');
                const day = String(currentDate.getDate()).padStart(2, '0');
                const hours = String(currentDate.getHours()).padStart(2, '0');
                const minutes = String(currentDate.getMinutes()).padStart(2, '0');
                const seconds = String(currentDate.getSeconds()).padStart(2, '0');
                const currentTime = new Date(new Date().getTime() + (8 * 60 * 60 * 1000)).toISOString().replace('T', ' ').substring(0, 19);
                var id = this.uid + new Date().getTime().toString();
                const newCard = {
                    id: id,
                    front: fronttextarea,
                    back: backtextarea,
                    time: currentTime,
                    updatetime: currentTime,
                    mark: 0
                };
                this.previewCards.unshift(newCard);
                this.savePreviewCardsToLocalStorage();
                alert("新增完成");

                console.log("同步到思维导图")
                let topicid = this.findTopicIdByCardId(id)
                //同步到思维导图
                this.addNewNodeToTopic({
                    text: fronttextarea.replace(/<\/?p>/g, ""),
                    id: id,
                    topicid: topicid,
                    fold: 0
                });

                this.save_xinzengids(id)
            } else alert("卡片名称冲突");
        },
        addNewNodeToTopic(newNode) {
            // Step 1: Create the new node JSON object
            const newNodeJson = {data:{
                    text: newNode.text,
                    id: newNode.id,
                    topicid: newNode.topicid,
                    fold: newNode.fold
                }};

            // Step 2: Retrieve the existing rootMind structure from localStorage
            const rootMindStr = localStorage.getItem('rootMind');
            const rootMind = JSON.parse(rootMindStr);

            // Step 3: Find the topic by topicid
            let foundTopic = null;
            const findTopic = (topics) => {
                topics.forEach(topic => {
                    if (topic.data.id === newNode.topicid) {
                        foundTopic = topic;
                    }
                    if (!foundTopic && topic.children) {
                        findTopic(topic.children);
                    }
                });
            };
            findTopic(rootMind.children); // Assuming rootMind.topics is an array of topics

            // Step 4: Add new node to the children array of the found topic
            if (foundTopic) {
                foundTopic.children = foundTopic.children || []; // Ensure there is a children array
                foundTopic.children.push(newNodeJson);
            } else {
                console.log('Topic not found');
                return; // Exit if no topic found
            }

            // Step 5: Save the updated rootMind back to localStorage
            localStorage.setItem('rootMind', JSON.stringify(rootMind));
        },
        findTopicIdByCardId(cardId) {
            // Step 1: Retrieve the zhuti object from localStorage
            const zhutiStr = localStorage.getItem('zhuti');
            const zhuti = JSON.parse(zhutiStr);
            const topics = zhuti.topics;

            // Helper function to search recursively
            function searchTopics(topics, cardId) {
                for (let topic of topics) {
                    // Check if this topic contains the cardId in the order field
                    if (topic.order && topic.order.split(',').includes(cardId)) {
                        return topic.topicid;  // Return the topicid if found
                    }
                    // Recursively search in children topics if they exist
                    if (topic.children && topic.children.length > 0) {
                        let foundTopicId = searchTopics(topic.children, cardId);
                        if (foundTopicId) {
                            return foundTopicId;  // Return the found topicid from children
                        }
                    }
                }
                return null;  // Return null if no matching topicid is found
            }

            // Start the recursive search from the root topics
            return searchTopics(topics, cardId);
        },
        deleteNodeAndPromoteChildren(targetNode) {
            // Step 1: Retrieve the existing rootMind structure from localStorage
            const rootMindStr = localStorage.getItem('rootMind');
            const rootMind = JSON.parse(rootMindStr);

            // Helper function to find and delete the node recursively
            const findAndDeleteNode = (node, parent = null) => {
                if (node.data.id === targetNode.id) {
                    if (parent) {
                        // Find the index of the node to be deleted
                        const index = parent.children.indexOf(node);
                        if (index > -1) {
                            // If the node is a folder (fold=1), remove it completely
                            if (node.data.fold === 1) {
                                parent.children.splice(index, 1);
                            } else {

                                // If the node has children, we need to promote them
                                if (node.children && node.children.length > 0) {
                                    // Remove the node and insert its children at the same position
                                    parent.children.splice(index, 1, ...node.children);
                                } else {
                                    // Just remove the node if there are no children to promote
                                    parent.children.splice(index, 1);
                                }
                                return true; // Node found and deleted, no need to continue
                            }
                        }
                    }
                    return true; // Node found and deleted, no need to continue
                }
                if (node.children) {
                    return node.children.some(child => findAndDeleteNode(child, node));  // Use `some` to stop recursion once true is returned
                }
                return false;
            };

            // Step 2: Start the recursive deletion from the root node
            if (!findAndDeleteNode(rootMind)) {
                console.log('Node not found');
                return; // Exit if no node found
            }

            // Step 3: Save the updated rootMind back to localStorage
            localStorage.setItem('rootMind', JSON.stringify(rootMind));
        },
        save_xinzengids(id) {
            if(id===null) return;
            var xinzengids = localStorage.getItem('xinzengids');
            if (xinzengids) {
                xinzengids = JSON.parse(xinzengids);
                //push的时候添加去重逻辑
                if (xinzengids.indexOf(id) === -1)
                    xinzengids.push(id);
            } else xinzengids = [id];
            localStorage.setItem('xinzengids', JSON.stringify(xinzengids));
        },

        qingkongxinzengkuang() {
            document.getElementById("fronttextareaxinzeng").value = "";
            var editor = tinymce.get('myTextareaxinzeng');
            if (editor) editor.setContent('');
        },
        sortPreviewCards() {
            return new Promise((resolve, reject) => {
                try {
                    const dangqianzhuti = localStorage.getItem('dangqianzhuti');
                    const cards = localStorage.getItem('cards') ? JSON.parse(localStorage.getItem('cards')) : {};
                    if (cards[dangqianzhuti] && cards[dangqianzhuti].order) {
                        const order = cards[dangqianzhuti].order.split(',');
                        const sortedPreviewCards = [];
                        if(order.length === this.previewCards.length){
                            order.forEach(id => {
                                console.log("🚀 ~ file: cardperform.html ~ line 514 ~ id: ", id);
                                const foundCard = this.previewCards.find(card => card.id === id);
                                console.log("🚀 ~ file: cardperform.html ~ line 516 ~ this.previewCards: ", this.previewCards);

                                if (foundCard) sortedPreviewCards.push(foundCard);
                            });
                            this.previewCards.splice(0, this.previewCards.length, ...sortedPreviewCards);
                            console.log("🚀 ~ file: cardperform.html ~ line 519 ~ sortedPreviewCards: ", sortedPreviewCards);
                        }
                    }

                    resolve(); // 解决 Promise
                } catch (error) {
                    console.error('Error:', error);
                    reject(error); // 捕获到异常时拒绝 Promise
                }
            });

        },
        async fetchData() {
            try {
                const query = {query: {bool: {must: [{match: {uid: localStorage.getItem('uid')}}]}}};
                const response = await axios.post(requesturl+'/proxy-search', query);
                console.log("🚀 ~ file: cardperform.html ~ line 567 ~ response: ", response);

                const cards = {};
                response.data.hits.hits.forEach(hit => {
                    const cardData = hit._source;
                    const key = cardData.front.split('：')[0];
                    const front = cardData.front.split('：')[1];
                    if (!cards[key]) cards[key] = {order: "", previewCards: []};
                    cardData.front = front;
                    cardData.back = cardData.back;
                    cardData.mark = cardData.known;
                    delete cardData.known;
                    cardData.id = cardData.sqlId;
                    delete cardData.sqlId;
                    cardData.time = cardData.createtime;
                    delete cardData.createtime;
                    cardData.updatetime = cardData.lastmodifieddate;
                    delete cardData.lastmodifieddate;
                    delete cardData.uid;
                    delete cardData.type;
                    cards[key].previewCards.push(cardData);
                });
                //从localstorage中获取cards命名为cardsLocal,然后进行两个cards的比较，进行cards和cardsLocal的合并，合并规则：比较两个cards中的previwCards中的卡片的id是否一样，如果id一样，那么比较updatetime时间，选择时间最新的一个
                // 获取本地存储中的卡片数据
                const cardsLocal = JSON.parse(localStorage.getItem('cards')) || {};

                // 合并cards和cardsLocal
                Object.keys(cards).forEach(key => {
                    if (!cardsLocal[key]) {
                        cardsLocal[key] = cards[key];
                    } else {
                        cards[key].previewCards.forEach(card => {
                            const localCardIndex = cardsLocal[key].previewCards.findIndex(localCard => localCard.id === card.id);
                            if (localCardIndex !== -1) {
                                // 如果本地卡片存在，比较更新时间
                                if (new Date(cardsLocal[key].previewCards[localCardIndex].updatetime) < new Date(card.updatetime)) {
                                    cardsLocal[key].previewCards[localCardIndex] = card; // 使用更新时间较新的卡片，解决断网后修改的问题
                                }
                            } else {
                                // 如果本地卡片不存在，则添加
                                cardsLocal[key].previewCards.push(card);
                            }
                        });
                    }
                });

                // 更新 localStorage 中的 cards
                this.saveTopicNameToCards(cardsLocal)
                localStorage.setItem('cards', JSON.stringify(cardsLocal));
                console.log("Updated cards: ", cardsLocal);
                console.log("🚀 ~ file: cardperform.html ~ line 604 ~ response: ", response);
                this.updateCardsOrderFromZhuti();

            } catch (error) {
                console.error('查询失败:', error);
            }
        },
        async fetchData1() {

            try {


                // console.log(alltopics)

                // const response = await axios.get(`${requesturl}/token_ret`);
                // const token = response.data.token;
                // axios.defaults.headers.common['Authorization'] = `${token}${this.uid}`;
            } catch (error) {
                console.error('Error fetching the token:', error);
            }
            return new Promise((resolve, reject) => {
                let alltopics = this.getAllTopicNamesFromZhuti()
                try {
                    const query = {
                        query: {
                            bool: {
                                must: [{match: {uid: localStorage.getItem('uid')}}]
                            }
                        },
                        size: 100
                    };

                    axios.post(requesturl+'/proxy-search', query)
                        .then(async response => {
                            console.log("Response: ", response);

                            const cards = {};
                            alltopics.forEach(topicName => {
                                cards[topicName] = {order: "", previewCards: []};
                            });
                            response.data.hits.hits.forEach(hit => {
                                const cardData = hit._source;
                                const key = cardData.front.split('：')[0];
                                const front = cardData.front.split('：')[1];
                                if (!cards[key]) cards[key] = {order: "", previewCards: []};
                                cardData.front = front;
                                cardData.back = cardData.back;
                                cardData.mark = cardData.known;
                                delete cardData.known;
                                cardData.id = cardData.sqlId;
                                delete cardData.sqlId;
                                cardData.time = cardData.createtime;
                                delete cardData.createtime;
                                cardData.updatetime = cardData.lastmodifieddate;
                                delete cardData.lastmodifieddate;
                                delete cardData.uid;
                                delete cardData.type;
                                cards[key].previewCards.push(cardData);
                            });


                            this.saveTopicNameToCards(cards)
                            localStorage.setItem('cards', JSON.stringify(cards));
                            console.log("Updated cards: ", cards);
                            await this.updateCardsOrderFromZhuti();

                            resolve(); // 成功解决 Promise
                        })
                        .catch(error => {
                            console.error('查询失败:', error);
                            reject(error); // 在错误情况下拒绝 Promise
                        });
                } catch (error) {
                    console.error('异常错误:', error);
                    reject(error); // 捕获到异常时拒绝 Promise
                }
            });
        },
        updateCardsOrderFromZhuti() {
            return new Promise((resolve, reject) => {
                try {
                    const zhutiStorage = localStorage.getItem('zhuti');
                    const dangqianzhuti = localStorage.getItem('dangqianzhuti');
                    let cards = localStorage.getItem('cards') ? JSON.parse(localStorage.getItem('cards')) : {};
                    if (zhutiStorage && dangqianzhuti) {
                        const zhuti = JSON.parse(zhutiStorage);
                        if (zhuti && zhuti.topics) {
                            zhuti.topics.forEach(topic => {
                                if (topic.topictitle === dangqianzhuti) {
                                    // 确保cards中有对应的键
                                    if (!cards[dangqianzhuti]) {
                                        cards[dangqianzhuti] = {};
                                    }
                                    cards[dangqianzhuti].order = topic.order;
                                }
                            });
                        }
                        this.saveTopicNameToCards(cards)
                        localStorage.setItem('cards', JSON.stringify(cards));
                    }

                    resolve(); // 解决 Promise
                } catch (error) {
                    console.error('Error:', error);
                    reject(error); // 捕获到异常时拒绝 Promise
                }
            });
        },
        async fetchAndStoreZhuti() {
            try {
                const query = {
                    query: {
                        bool: {
                            must: [{match: {id: localStorage.getItem('uid')}}]
                        }
                    }
                };

                const response = await axios.post(requesturl+'/proxy-user-order-r', query);

                // 假设返回的内容数组中的 JSON 对象只有一个
                if (response.data.hits.hits.length > 0) {
                    const zhutiData = JSON.parse(response.data.hits.hits[0]._source.zhuti);
                    console.log("🚀 ~ file: cardperform.html ~ line 741 ~ zhutiData: ", zhutiData);
                    //todo 取出zhutiData中的所有edittime最大的一个，跟当前localstorage中的zhuti中的所有的edittime中最大的一个进行对比，如果localstorage中的zhuti中的最大的edittime大于等于当前的最大的edittime，那么就不进行替换，否则进行替换。
                    // 获取zhutiData中最大的edittime
                    console.log("🚀 ~ file: cardperform.html ~ line 783 ~ zhutiData.topics: ", zhutiData);
                    const maxEditTimeZhutiData = Math.max(...zhutiData.topics.map(topic => new Date(topic.edittime).getTime()));

                    console.log("🚀 ~ file: cardperform.html ~ line 783 ~ maxEditTimeZhutiData: ", maxEditTimeZhutiData);

                    // 获取localStorage中zhuti的最大edittime
                    const localZhuti = JSON.parse(localStorage.getItem('zhuti')) || {"topics": []};
                    const maxEditTimeLocalZhuti = localZhuti.topics.length > 0
                        ? Math.max(...localZhuti.topics.map(topic => new Date(topic.edittime).getTime()))
                        : 0;
                    console.log("🚀 ~ file: cardperform.html ~ line 788 ~ maxEditTimeLocalZhuti: ", maxEditTimeLocalZhuti);
                    // 对比edittime，如果需要则更新localStorage中的zhuti
                    if (maxEditTimeZhutiData > maxEditTimeLocalZhuti) {
                        localStorage.setItem('zhuti', JSON.stringify(zhutiData));
                    }
                } else {
                    console.log('未找到匹配的数据');
                }
            } catch (error) {
                console.error('查询失败:', error);
                alert("检查网络是否连接失败")
            }
        },
        fetchAndStoreZhuti1() {
            return new Promise(async (resolve, reject) => {

                const response = await axios.get(`${requesturl}/token_ret`);
                const token = response.data.token;
                axios.defaults.headers.common['Authorization'] = `${token}${this.uid}`;
                const query = {
                    query: {
                        bool: {
                            must: [{match: {id: localStorage.getItem('uid')}}]
                        }
                    }, size: 100
                };

                axios.post(requesturl + '/proxy-user-order-r', query)
                    .then(async response => {
                        let maxEditTimeLocalZhuti = 0;
                        if (response.data.hits.hits.length > 0) {
                            const zhutiData = JSON.parse(response.data.hits.hits[0]._source.zhuti);

                            //

                            if (zhutiData) {
                                if (zhutiData.personalImg) {
                                    if (document.getElementById('imgpersonheader')) {
                                        document.getElementById('imgpersonheader').src = zhutiData.personalImg;
                                        document.getElementById('imgpersonheader').srcset = zhutiData.personalImg;
                                    }

                                    // 替换完成之后 将加载中动画状态 none 修改为block   personaljiazai
                                }
                                if (zhutiData.rootMind) {
                                    localStorage.setItem('rootMind', JSON.stringify(zhutiData.rootMind))
                                }
                            }


                            console.log("zhutiData: ", zhutiData);
                            //用作切换主题
                            this.topics = zhutiData.topics;

                            const maxEditTimeZhutiData = Math.max(...zhutiData.topics.map(topic => new Date(topic.edittime).getTime()));

                            const localZhuti = JSON.parse(localStorage.getItem('zhuti')) || {"topics": []};
                            maxEditTimeLocalZhuti = localZhuti.topics.length > 0
                                ? Math.max(...localZhuti.topics.map(topic => new Date(topic.edittime).getTime()))
                                : 0;

                            if (maxEditTimeZhutiData > maxEditTimeLocalZhuti) {
                                localStorage.setItem('zhuti', JSON.stringify(zhutiData));
                            }
                            await this.updateCardsOrderFromZhuti()
                            //将maxEditTimeZhutiData保存到localStorage中，以便下次比较
                            localStorage.setItem('maxEditTimeZhuti', maxEditTimeZhutiData);
                            resolve(); // 成功解决Promise
                        } else {
                            localStorage.setItem('maxEditTimeZhuti', maxEditTimeLocalZhuti);
                            console.log('未找到匹配的数据');
                            resolve(); // 未找到数据也视为解决Promise
                        }
                    })
                    .catch(error => {
                        console.error('查询失败:', error);
                        reject(error); // 发生错误时拒绝Promise
                    });


            });
        },
        // editTitleChange(){
        //
        // },
        // searchCards(){},
        pageInit() {
            return new Promise((resolve, reject) => {
                //初始化思维导图

                this.initSuoyouKapian()
                console.log("🚀 ~ file: cardperform.html ~ line 739 ~ pageInit: ");
                this.dangqianzhuti = localStorage.getItem('dangqianzhuti');
                this.dangqianzhutititle = localStorage.getItem('dangqianzhutititle');
                console.log("🚀 ~ file: cardperform.html ~ line 741 ~ dangqianzhuti: ", this.dangqianzhuti);
                let previewCardsFromStorage = [];
                let cards = localStorage.getItem('cards') ? JSON.parse(localStorage.getItem('cards')) : {};
                if (cards[this.dangqianzhuti] && cards[this.dangqianzhuti].previewCards) {

                    previewCardsFromStorage = cards[this.dangqianzhuti].previewCards;
                    this.orderFromStorage = cards[this.dangqianzhuti].order;
                }
                ;
                if (previewCardsFromStorage.length > 0) {
                    localStorage.setItem('previewCards', JSON.stringify(previewCardsFromStorage));
                } else {
                    localStorage.setItem('previewCards', JSON.stringify([]));
                }
                ;const storedCards = localStorage.getItem('previewCards');
                console.log("🚀 ~ file: cardperform.html ~ line 757 ~ storedCards: ", storedCards);
                if (storedCards) {
                    try {
                        this.previewCards = [...JSON.parse(storedCards)];
                        console.log("🚀 ~ file: cardperform.html ~ line 761 ~ JSON.parse(storedCards): ", JSON.parse(storedCards));
                        if(this.previewCards.length-1<this.currentIndex){
                            this.currentIndex = 0
                        }
                        this.zhongjianka = this.currentCard;
                        // this.sortPreviewCards();
                        resolve(); // 解决 Promise
                    } catch (error) {
                        console.error('Error:', error);
                        reject(error); // 如果有错误，拒绝 Promise
                    }
                } else {
                    resolve(); // 如果没有存储的卡片，也解决 Promise
                }
                //chatgpt 初始化
                localStorage.setItem('currentCard',JSON.stringify(this.currentCard))
                localStorage.setItem('currentIndex',this.currentIndex)

               // 测试思维导图初始化
               //  this.$q = Quasar;
               //  this.root = {"data":{"text":"test测试"},"children":[{"data":{"id":7466,"back":"<p>3</p>","mindmapLayer":0,"mindmapParentId":0,"mindmapSameLevelId":7471,"listSameLevelId":-1,"text":"3"},"children":[{"data":{"id":7469,"back":"<p>66</p>","mindmapLayer":1,"mindmapParentId":7466,"mindmapSameLevelId":7467,"listSameLevelId":-1,"text":"6 0"},"children":[]},{"data":{"id":7467,"back":"<p>5</p>","mindmapLayer":1,"mindmapParentId":7466,"mindmapSameLevelId":7469,"listSameLevelId":0,"text":"4"},"children":[]},{"data":{"id":7471,"back":"<p>8</p>","mindmapLayer":1,"mindmapParentId":7466,"mindmapSameLevelId":7469,"listSameLevelId":0,"text":"8"},"children":[{"data":{"id":7465,"back":"<p>222</p>","mindmapLayer":2,"mindmapParentId":7471,"mindmapSameLevelId":7468,"listSameLevelId":-1,"text":"2"},"children":[]},{"data":{"id":7464,"back":"<p>1</p>","mindmapLayer":2,"mindmapParentId":7471,"mindmapSameLevelId":7466,"listSameLevelId":-1,"text":"1"},"children":[]}]},{"data":{"id":7472,"back":"<p>9</p>","mindmapLayer":1,"mindmapParentId":7466,"mindmapSameLevelId":7471,"listSameLevelId":0,"text":"9"},"children":[]},{"data":{"id":7470,"back":"<p>7</p>","mindmapLayer":1,"mindmapParentId":7466,"mindmapSameLevelId":7471,"listSameLevelId":0,"text":"7"},"children":[]},{"data":{"id":7468,"back":"<p>5</p>","mindmapLayer":1,"mindmapParentId":7466,"mindmapSameLevelId":7467,"listSameLevelId":0,"text":"51"},"children":[]}]}],"_updata":true};
               //  this.theme = "fresh-green-compat";


            });

        },
        initSuoyouKapian() {
            // 创建一个虚拟主题名称，用于表示所有卡片
            const virtualTopicName = "所有卡片";

            // 尝试从localStorage中获取cards
            let cards = localStorage.getItem('cards') ? JSON.parse(localStorage.getItem('cards')) : {};

            // 创建一个新的previewCards数组，用于存放所有卡片
            let allPreviewCards = [];

            // 遍历cards中的每个主题，将其previewCards合并到allPreviewCards中1
            Object.keys(cards).forEach(key => {
                if (key === "所有卡片") return;
                const topic = cards[key];
                if (topic && topic.previewCards) {
                    allPreviewCards = allPreviewCards.concat(topic.previewCards);
                }
            });

            // 创建虚拟主题，并将所有卡片的数组赋值给它
            const virtualTopic = {
                order: '', // 虚拟主题可以没有顺序
                previewCards: allPreviewCards
            };

            // 将虚拟主题添加到cards对象中
            cards[virtualTopicName] = virtualTopic;

            // 更新localStorage
            this.saveTopicNameToCards(cards)
            localStorage.setItem('cards', JSON.stringify(cards));
        },
        updateCurrentTopicByCardId(cardId) {
            console.log("🚀 ~ file: perform-vue.js ~ line 731 ~ cardId: ",cardId);
            let cards = localStorage.getItem('cards') ? JSON.parse(localStorage.getItem('cards')) : {};
            let foundTopic = null;

            // 遍历cards对象，查找包含指定卡片ID的主题
            for (let topicKey in cards) {
                if (cards.hasOwnProperty(topicKey) && topicKey !== "所有卡片") {
                    let topic = cards[topicKey];
                    // 假设每个主题下有previewCards数组包含卡片信息
                    let cardExistsInTopic = topic.previewCards.some(card => card.id === cardId);
                    if (cardExistsInTopic) {
                        foundTopic = topicKey; // 找到卡片所属的主题
                        break; // 找到后退出循环
                    }
                }
            }

            // 更新Vue组件的currentTopic数据属性
            if (foundTopic !== null) {
                this.dangqianzhuti = foundTopic;
                this.dangqianzhutititle = foundTopic;
            } else {
                this.dangqianzhuti = '未知主题'; // 如果没找到，可以设为未知或其他默认值
                this.dangqianzhutititle = '未知主题';
            }
        },
        initauth() {
            return new Promise(async (resolve, reject) => {
                // 模拟异步数据请求
                const response = await axios.get(`${requesturl}/token_ret`);
                const token = response.data.token;
                axios.defaults.headers.common['Authorization'] = `${token}${this.uid}`;

            });
        }


    },
    mounted() {

        localStorage.removeItem("cards")
        localStorage.removeItem("zhuti")


        var self = this
        const uid = localStorage.getItem('uid');
        if (uid) {
            this.uid = uid
        } else {

            Swal.fire({
                title: '未登录',
                text: '即将跳转登录页面，推荐使用微信扫码登录',
                icon: 'info',
                confirmButtonText: '好的'
            }).then((result) => {
                if (result.value) {
                    window.location.href = '/loginorregistry'; // 这里的 '/login' 是你希望跳转到的URL
                }
            });
        }



        //cards中如果不存在"所有卡片"的主题的话，初始化一个所有卡片的主题
        let cards = localStorage.getItem('cards') ? JSON.parse(localStorage.getItem('cards')) : {};




        //

        // localStorage.setItem('dangqianzhuti', "webflow"); fetchData1

        //
        this.fetchAndStoreZhuti1().then(() => {
            this.fetchData1().then(() => {
                this.pageInit().then(() => {

                    //



                    this.sortPreviewCards().then(() =>
                    {
                        //初始化的时候初始previewCards顺序就行了,上边那个排序没有用，但不删，因为我也不想看会不会影响别的逻辑
                        const order = this.getOrderFromZhuti(localStorage.getItem('dangqianzhuti'));
                        if (order) {
                            // 根据order排序cards
                            this.previewCards.sort((a, b) => order.indexOf(a.id) - order.indexOf(b.id));
                        }

                        this.ifbianjidonghua = false
                        const previewCards = JSON.parse(localStorage.getItem('previewCards') || '[]');
                        if (previewCards.length > 0) {
                            this.ifbianji= false

                            // document.getElementById('jiazaizhongdonghua').style.display = 'none';
                            localStorage.setItem('initTinyMCE', 'false');
                        }else{
                            localStorage.setItem('initTinyMCE', 'true');
                        }

                        // 加载中图片效果取消
                        const elements = document.querySelectorAll('.jiazaizhongbg');
                        // 遍历所有获取到的元素
                        if(elements){
                            elements.forEach(function(element) {
                                // 设置display属性为none
                                element.style.display = 'none';
                            });
                        }
                    })
                })
            })
        })

        this.pageInit()
    },

});

function cards2ESTurn(){

    const cards1 = JSON.parse(localStorage.getItem('cards'));

    if (cards1 && typeof cards1 === 'object') {
        let latestUpdateTime = new Date(0); // 设置初始最早的时间
        let latestCardId = null;
        Object.keys(cards1).forEach(key => {
            let card = cards1[key];
            //如果card下的previewCards不存在
            if (card.previewCards !== undefined) {
                card.previewCards.forEach(previewCard => {
                    if ('front' in previewCard) previewCard.front = key + '：' + previewCard.front;
                    ;
                    if ('mark' in previewCard) {
                        previewCard.known = previewCard.mark;
                        delete previewCard.mark;
                    }
                    ;
                    if ('id' in previewCard) {
                        previewCard.sqlId = previewCard.id;
                        delete previewCard.id;
                    }
                    ;
                    if ('time' in previewCard) {
                        previewCard.createtime = previewCard.time;
                        delete previewCard.time;
                    }
                    ;
                    if ('lastmodifieddate' in previewCard) {
                        previewCard.lastmodifieddate = previewCard.lastmodifieddate;
                        delete previewCard.updatetime;
                        delete previewCard.icon;
                        delete previewCard.size;
                    }
                    ;previewCard.uid = this.uid;
                    previewCard.type = 1;


                    // 更新最近修改的卡片ID
                    const currentUpdateTime = new Date(previewCard.lastmodifieddate);
                    if (currentUpdateTime > latestUpdateTime) {
                        latestUpdateTime = currentUpdateTime;
                        latestCardId = previewCard.sqlId;
                    }

                });
            }
        });
        console.log("🚀 ~ file: cardperform.html ~ line 428 ~ latestCardId: ", latestCardId);
        // this.save_xinzengids(latestCardId) todo 有争议需要讨论
        localStorage.setItem('cards2es', JSON.stringify(cards1))

    }


}

async function push2es() {













    // cards2ESTurn()
    let xinzengids = localStorage.getItem('xinzengids') ? JSON.parse(localStorage.getItem('xinzengids')) : [];
    if (!xinzengids.length) return;
    // 复制待新增的ID列表
    const idsToAdd = [...xinzengids];
    console.log("待批量新增的卡片IDs: ", idsToAdd);
    const cards2es = JSON.parse(localStorage.getItem('cards2es'));
    console.log("🚀 ~ file: cardperform.html ~ line 442 ~ cards2es: ", cards2es);
    let bulkBody = '';
    const now = new Date().getTime();

    Object.keys(cards2es).forEach(key => {
        if (key === "所有卡片") return;
        if(cards2es[key].previewCards!=undefined){
            cards2es[key].previewCards.forEach(card => {
                console.log("🚀 ~ file: cardperform.html ~ line 449 ~ card: ", card);
                // 从ids字符数组中拿到待新增的数组内容，
                if (idsToAdd.includes(card.sqlId)) {
                    bulkBody += JSON.stringify({index: {_index: 'users', _type: '_doc', _id: card.sqlId}}) + '\n';
                    bulkBody += JSON.stringify(card) + '\n';
                }
            });}
    });

    if (bulkBody) {
        console.log("🚀 ~ file: cardperform.html ~ line 459 ~ bulkBody: ", bulkBody);
        axios.post(requesturl+'/proxy-bulk', bulkBody, {
            headers: {'Content-Type': 'application/x-ndjson'}
        }).then(response => {
                console.log('Bulk operation successfully executed', response.data);
                // 从xinzengids数组中移除已新增的IDs
                xinzengids = xinzengids.filter(id => !idsToAdd.includes(id));
                localStorage.setItem('xinzengids', JSON.stringify(xinzengids));
            }
        ).catch(error => console.error('Failed to execute bulk operation', error));
    }
}

// 定时任务
setInterval(push2es, 1000 * 10 ); // 每3分钟执行一次


// 修改后的deleteEsIds方法


async function deleteEsIds() {


    let shanchu = localStorage.getItem('shanchu') ? JSON.parse(localStorage.getItem('shanchu')) : [];


    if (!shanchu.length) return;

    // 复制待删除的ID列表
    const idsToDelete = [...shanchu];
    console.log("🚀 ~ file: cardperform.html ~ line 594 ~ idsToDelete: ", idsToDelete);
    //从localstorage中获取xinzengids
    const xinzengids = localStorage.getItem('xinzengids') ? JSON.parse(localStorage.getItem('xinzengids')) : [];
    let bulkDeleteBody = '';
    idsToDelete.forEach(id => {
        //如果xinzengids中包含这个id则不执行删除这个id
        if (xinzengids.includes(id)) {
            console.log('Skipping deletion of ID ' + id + ' because it is in the xinzengids list.');
            return;
        }
        bulkDeleteBody += JSON.stringify({delete: {_index: 'users', _type: '_doc', _id: id}}) + '\n';
    });


    if (bulkDeleteBody) {
        axios.post(requesturl+'/proxy-bulk', bulkDeleteBody, {
            headers: {'Content-Type': 'application/x-ndjson'}
        }).then(response => {
            console.log('Bulk delete operation successfully executed', response.data);
            // 从shanchu数组中移除已删除的IDs
            shanchu = shanchu.filter(id => !idsToDelete.includes(id));
            localStorage.setItem('shanchu', JSON.stringify(shanchu));
        }).catch(error => console.error('Failed to execute bulk delete operation', error));
    }
}

// 设置定时任务，定期调用deleteEsIds
setInterval(deleteEsIds, 1000 * 20); // 比如每两分钟执行一次


function saveZhutiToElasticsearch() {
    const zhuti = localStorage.getItem('zhuti');
    const uid = localStorage.getItem('uid');

    const localZhuti = JSON.parse(localStorage.getItem('zhuti')) || {"topics": []};
    var maxEditTimeLocalZhuti = localZhuti.topics.length > 0
        ? Math.max(...localZhuti.topics.map(topic => new Date(topic.edittime).getTime()))
        : 0;
    //获取maxEditTimeZhuti并和maxEditTimeLocalZhuti进行比较，如果maxEditTimeZhuti大于maxEditTimeLocalZhuti，则说明有新的数据需要同步到Elasticsearch
    const maxEditTimeZhuti = localStorage.getItem('maxEditTimeZhuti') || 0;
    if (maxEditTimeZhuti < maxEditTimeLocalZhuti) {

        if (zhuti && uid) {
            const data = {
                id: uid,
                zhuti: zhuti
            };

            axios.post(requesturl+'/proxy-user-order-cud', data).then(response => {
                console.log('Data successfully saved to Elasticsearch', response.data);
                //更新maxEditTimeZhuti
                localStorage.setItem('maxEditTimeZhuti', maxEditTimeLocalZhuti);
            }).catch(error => {
                console.error('Failed to save data to Elasticsearch', error);
            });

        }
    } else {
        console.log("no new zhuti data to save")
    }
}

// 设置定时任务，每5分钟执行一次
setInterval(saveZhutiToElasticsearch, 20000);
// 你可以使用beforeunload事件来监控页面退出的动作,成功了，关闭的时候执行发送了。
window.addEventListener('beforeunload', function (event) {
    // 在这里编写你的函数代码
    push2es()
    deleteEsIds()
    localStorage.setItem('maxEditTimeZhuti', '0');
    saveZhutiToElasticsearch()
});

function updateOnlineStatus() {
    if (!navigator.onLine) {
        // 当用户处于离线状态时
        alert("网络异常，请检查您的网络连接！");
    }
}

// 监听网络状态变化事件
window.addEventListener('online', updateOnlineStatus);
window.addEventListener('offline', updateOnlineStatus);

// 初始检查
updateOnlineStatus();


function tinymcechushihuamyTextarea(idString,sfjixu) {
    var globalFunctionRequestReplaceExpressProxy="http://baota.memlee.top:4000"
    var imageCompression = function(base64, w){
        return new Promise(function(resolve, reject) {
            console.log("enter promise")
            var newImage = new Image();
            var quality = 0.6;
            console.log("压缩前",imgPasteUrl.length/1024)
            newImage.src = imgPasteUrl;
            newImage.setAttribute("crossOrigin", 'Anonymous');
            var imgWidth, imgHeight;
            newImage.onload = function () {
                imgWidth = this.width; imgHeight = this.height;
                var canvas = document.createElement("canvas");
                var ctx = canvas.getContext("2d");
                if (Math.max(imgWidth, imgHeight) > w)
                {if (imgWidth > imgHeight)
                {canvas.width = w; canvas.height = w * imgHeight / imgWidth;}
                else
                {canvas.height = w; canvas.width = w * imgWidth / imgHeight;}
                }
                else
                {canvas.width = imgWidth; canvas.height = imgHeight; }
                ctx.clearRect(0, 0, canvas.width, canvas.height);
                ctx.drawImage(this, 0, 0, canvas.width, canvas.height);
                var base64 = canvas.toDataURL("image/jpeg", quality);
                if (base64.length / 1024 > 1024) {
                    quality = (1024-200)/(base64.length / 1024)
                    base64 = canvas.toDataURL("image/jpeg", quality);
                }
                if (base64.length / 1024 < 50) {
                    quality = 50+20/(base64.length /1024 )
                    base64 = canvas.toDataURL("image/jpeg", quality);
                }
                resolve(base64);
            }
        })
    }
    var imgPasteUrl = ""   //全局变量用于存储上传图片路径
    function uploadImg2Gitee(img, success, failure,loadingNotification) {
        var base64 = img.split(",")[1];
        var requesturl1 =
            "https://jr9nqpz4-8083.asse.devtunnels.ms"


        // $.ajax({
        //     //requesturl+"upload-image-gitee"、upload_image_to_oss
        //     // url: requesturl+"/upload-image-gitee",  // 更改为后端新建的路由 之前的方式
        //     url: requesturl+"/upload_image_to_oss",  // 更改为后端新建的路由
        //     type: "post",
        //     data: JSON.stringify({"content": base64}),
        //     dataType: 'json',
        //     processData: false,
        //     async: false,
        //     contentType: "application/json;charset=UTF-8",
        //     success: function(data) {
        //         var imgSrc = data.imgSrc;  // 使用后端返回的imgSrc
        //         loadingNotification.close()
        //         success(imgSrc);
        //     },
        //     error: function(e) {
        //         alert("上传图片失败");
        //         loadingNotification.close()
        //         console.log(e);
        //         failure(e);
        //     }
        // });


        const url = `${requesturl}/upload_image_to_oss`;
        const data = JSON.stringify({ "content": base64 });

        axios.post(url, data, {
            headers: {
                'Content-Type': 'application/json'
            }
        })
            .then(response => {
                const imgSrc = response.data.imgSrc; // 使用后端返回的imgSrc
                loadingNotification.close(); // 假设你有一个关闭加载通知的函数
                success(imgSrc); // 假设这是成功处理的回调函数
            })
            .catch(error => {
                alert("上传图片失败");
                loadingNotification.close(); // 同上，假设关闭加载通知的函数
                console.error(error);
                failure(error); // 假设这是失败处理的回调函数
            });



    }
    var ifInline = false;
    if(sfjixu==3){
        ifInline=true
    }
    // 在这里编写函数的代码
    tinymce.init({
        selector: idString, // 指定要初始化的<textarea>元素的ID
        inline: ifInline,
        mobile: {
            menubar: true
        },
        language_url: requesturl+'/static/tinymce-lang-zh@5.2.2.js', // 指定语言文件的URL https://cdn.jsdelivr.net/gh/wt-sml/wutong_cdn/js/tinymce-lang-zh@5.2.2.js
        language: 'zh_CN', // 设置语言为中文
        skin_url: requesturl+'/static/skin.min.css', // 指定皮肤文件的URL
        height: 400, // 设置编辑器高度
        plugins: [
            "advlist autolink lists link image axupimgs charmap preview hr anchor",
            "searchreplace wordcount visualblocks visualchars code fullscreen",
            "insertdatetime nonbreaking save table contextmenu directionality",
            "emoticons paste textcolor colorpicker textpattern code lineheight"
        ],
        content_style: 'img {  max-width: 100%;  height: auto; }',
        textpattern_patterns: [
            {start: '*', end: '*', format: 'italic'},
            {start: '**', end: '**', format: 'bold'},
            {start: '#', format: 'h1'},
            {start: '##', format: 'h2'},
            {start: '###', format: 'h3'},
            {start: '####', format: 'h4'},
            {start: '#####', format: 'h5'},
            {start: '######', format: 'h6'},
            {start: '1. ', cmd: 'InsertOrderedList'},
            {start: '* ', cmd: 'InsertUnorderedList'},
            {start: '- ', cmd: 'InsertUnorderedList'},
            {start: '//brb', replacement: 'Be Right Back'}
        ],
        toolbar:
            'image axupimgs  | undo redo | bold italic underline strikethrough | fontsizeselect | forecolor backcolor | alignleft aligncenter alignright alignjustify | bullist numlist | outdent indent blockquote | link unlink code | removeformat',
        branding: false,
        menubar: true,
        images_upload_handler: async (blobInfo, success, failure) => {
            // 显示正在加载的提示

            const loadingNotification = tinymce.get(idString.replace(/#/g, "")).notificationManager.open({
                text: '正在粘贴图片...',
                type: 'info',
                closeButton: false,
            });
            var img = ""

            if (blobInfo.base64 != undefined) {
                img = 'data:image/jpeg;base64,' + blobInfo.base64()
            } else {
                var asyncReader = function(){
                    return new Promise(function(resolve,reject){
                        const reader = new FileReader();
                        reader.addEventListener('load', async () => {
                            img = reader.result + ''
                            //在这里使用压缩算法
                            imgPasteUrl = img
                            img = await imageCompression(img, 1400)
                            console.log("压缩后", img.length / 1024);
                            resolve(img)
                        });
                        reader.readAsDataURL(blobInfo.blob());
                    })
                }
                img =  await asyncReader()
            }
            if (img != "") {
                imgPasteUrl = img
                img = await imageCompression(img, 1400)
                console.log("压缩后", img.length / 1024);
                console.log("center")
                console.log("end")
            }
            uploadImg2Gitee(img, success, failure,loadingNotification);



        },
        paste_data_images: true,
        paste_preprocess: async function (plugin, args) {
        },
        images_upload_credentials: true,
        images_reuse_filename: true,
        image_advtab: true,
        images_upload_base_path: '',
        images_upload_url: 'doFileUpload.asp',
        automatic_uploads: true,
        file_picker_types: 'file, image, media',
        file_picker_callback: function (callback, value, meta) {
        },
        images_dataimg_filter: function (img) {
            //可以在这里把文件上传，使用全局参数保存路径，最后在处理的时候替换img.src实现
            imgPasteUrl = img
            return !img.hasAttribute('internal-blob');  // blocks the upload of <img> elements with the attribute "internal-blob".
        },
        init_instance_callback: function (editor) {
            if(sfjixu===1){
                tinymcechushihuamyTextarea("#myTextareaxinzeng",0)
                const initTinyMCE = localStorage.getItem('initTinyMCE') === 'true';
                if (initTinyMCE) {
                    // document.getElementById('jiazaizhongdonghua').style.display = 'none';
                    // 完成后，重置标志以避免影响后续逻辑
                    localStorage.setItem('initTinyMCE', 'false');
                }
                // document.getElementById('jiazaizhongdonghua').style.display = 'none';
                console.log('TinyMCE 初始化完成');
            }
        }
    });
}
// window.onload = function() {// myTextareaxinzeng
//     tinymcechushihuamyTextarea("#myTextarea", 1)
//     document.getElementById("guodudonghua").style.display='none'
//     document.getElementById("xiangqingye").style.display='block'
// }


document.addEventListener('DOMContentLoaded', (event) => {



    tinymcechushihuamyTextarea("#myTextarea", 1)



    document.getElementById("guodudonghua").style.display='none'
    document.getElementById("xiangqingye").style.display='block'
    var myDiv = document.getElementById('bianjimoshi');
    myDiv.addEventListener('click', function() {
        // alert('div被点击了！');
        // tinymcechushihuamyTextarea('#beimianbianji',3)

        // 添加功能#cardbackdiv
        if(document.getElementById("cardbackdiv").style.display==='block'){
            alert("模式已切换，请返回卡片正面查看")
        }


    });
})


//监听并改变布局。监听改变过程+perform流程
document.addEventListener('DOMContentLoaded', (event) => {
    // 修改，展示效果修改，展示效果和tinymce一致
    const divElement = document.querySelector('.beimianxiaoguodonghuaquchu');

    divElement.style.display = 'flex';
    divElement.style.flexDirection = 'column';
    divElement.style.flexWrap = 'nowrap';
    divElement.style.alignItems = 'flex-start';

    function checkScrollbar() {
        if (divElement.scrollHeight > divElement.clientHeight) {
            divElement.style.justifyContent = 'space-between';
        } else {
            divElement.style.justifyContent = 'center';
        }
    }

    const observer = new MutationObserver(checkScrollbar);

    observer.observe(divElement, { childList: true, subtree: true });
    divElement.addEventListener('scroll', checkScrollbar);
    window.addEventListener('resize', checkScrollbar);

    window.addEventListener('load', checkScrollbar);
    window.addEventListener('load', () => {
        setTimeout(checkScrollbar, 1000); // 延迟 1 秒调用
    });
//
    var myDiv = document.getElementById('bianjimoshi');
    myDiv.addEventListener('click', function () {
        if (document.getElementById('cardbackdiv').style.display === 'block') {
            // 修改 id 为 kapianzhengmian 的元素的样式
            const frontElement = document.getElementById('kapianzhengmian');
            if (frontElement) {
                frontElement.style.transform =
                    'translate3d(0px, 0px, 0px) scale3d(1, 1, 1) rotateX(0deg) rotateY(0deg) rotateZ(0deg) skew(0deg, 0deg)';
                frontElement.style.transformStyle = 'preserve-3d';
                frontElement.style.display = 'block';
            }

            // 修改 id 为 cardbackdiv 的元素的样式
            const backElement = document.getElementById('cardbackdiv');
            if (backElement) {
                backElement.style.transform =
                    'translate3d(0px, 0px, 0px) scale3d(1, 1, 1) rotateX(0deg) rotateY(-90deg) rotateZ(0deg) skew(0deg, 0deg)';
                backElement.style.transformStyle = 'preserve-3d';
                backElement.style.display = 'none';
            }
        }


        //
        // 获取 id 为 qiehuanfuximoshi 的元素
        const divElement = document.getElementById('qiehuanfuximoshi');

        if (divElement) {
            // 修改上边框颜色和宽度
            divElement.style.borderTopColor = '#696969'; // 黑灰色
            divElement.style.borderTopWidth = '1px';
            divElement.style.borderTopStyle = 'solid'; // 确保边框样式为实线
        }


// class 为 div-block-53 的元素 修改display 为flex
        const elements = document.getElementsByClassName('div-block-53');

// 遍历所有匹配的元素，并修改它们的 display 样式
        for (let i = 0; i < elements.length; i++) {
            elements[i].style.justifyContent = 'space-between';
        }

    });

})






document.getElementById('toggle-checkboxes-btn').addEventListener('click', function() {
  // 获取所有的多选框
  var checkboxes = document.querySelectorAll('.card-checkbox');
  // 判断当前多选框的显示状态，并切换
  if (checkboxes.length > 0 && checkboxes[0].style.display === 'none') {
    checkboxes.forEach(function(checkbox) {
      checkbox.style.display = 'inline'; // 显示多选框
    });
  } else {
    checkboxes.forEach(function(checkbox) {
      checkbox.style.display = 'none'; // 隐藏多选框
    });
  }
});


// 反转回反面的时候，没有显示全上方

var div = document.getElementById('kapianzhengmian');
div.addEventListener('click', function() {
    // 设置延时执行
    setTimeout(function() {

        const divElement1 = document.querySelector('.beimianxiaoguodonghuaquchu');
        if (divElement1.scrollHeight > divElement1.clientHeight) {
            divElement1.style.justifyContent = 'space-between';
        } else {
            divElement1.style.justifyContent = 'center';
        }
    }, 300); // 延时5000毫秒，即5秒
});
